OS X games from the ground up: loops

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: more on decisions and functions

In the previous post you made improvements to the code that reads and validates the command line. Now that we have the number of phrases the learner wants to see, it’s time to do something with it.

Change your code so it looks like this:

The changed code is between lines 46 and 55.

You’ve seen how we can control whether a block of code gets executed by using if and else commands. Sometimes we need to execute a block of code multiple times. This is exactly the situation we have here. We want to execute line 53 as many times as it takes to display the number of phrases requested by the user. One way to do that is with a while command. While works in a similar way to if, in that it has a condition in parentheses followed by a body between braces. However, whereas if will execute the statements in its body once if the condition is true, while will execute the code in its body repeatedly while the condition is true.

Let’s assume that the user has requested two phrases and follow the code through step by step to see what happens. In line 50 we declare and initialise a counter called i. The counter will keep track of the number of phrases we’ve displayed. In line 52 the while command checks to see if i is less than numberOfPhrases. It is, because i is currently 0 and numberOfPhrases is 2. So the body (lines 53 and 54) is executed.

The first line of this code displays a randomly generated phrase – you’re already familiar with this line from previous posts. The second line introduces a new operator, the increment operator ++. The statement i++ is equivalent to i = i + 1. The reason we have a special operator for it is that adding 1 to a variable is something you end up doing a lot in code. There’s also an equivalent decrement operator, --, which subtracts 1 from a variable. So what this second line is doing, is adding 1 to our counter because we’ve just displayed a phrase.

One important thing to note about the increment and decrement operators is that they can work in two different ways, with the operator placed either before the variable, e.g. ++i, or after the variable, e.g. i++. These both do the same thing if they are used on their own in a statement, the difference comes when they are used in an expression and/or an assignment. When the prefix form is used, ++i, the value of i used in the expression or assignment will be its value after it has been incremented. In other words, this code:

would display “result is 4 and i is 2”.

If you use the postfix form, i++, the value of i used in the expression or assignment will be its value before it is incremented. So, this code:

would display “result is 3 and i is 2”.

OK, back to our Buzzword code. Now we reach the end of the body, marked by the closing brace on line 55. Instead of continuing with the next bit of code outside the braces, as we would do with an if command, control is passed back to the while command on line 52, which once again checks to see if i < numberOfPhrases.  It is, because i is now 1 and numberOfPhrases is 2.

So the body is executed once more. A second phrase is printed and i is incremented, so it now equals 2.

Once again we reach the end of the body and go back to the while command on line 52. This time, when the condition is checked, i is not less than numberOfPhrases, because they both now equal 2. So now the body is not executed and control passes to the statement following the closing brace, which in our case is the return statement on line 57.

Edit the scheme and change the argument to a single digit number, say 5. Now build and run the code. You should get something like this:

Buzzword loop five times

Count the phrases and satisfy yourself that you have exactly five, no more, no less.

Here’s another example of a while loop:

Take a close look at this loop and see if you can work out what number will get displayed by the printf command in line 11.

If you said 5, then well done, you’re starting to get the hang of loops, but you missed something that would prevent this from happening. If you said the number will never get displayed, then my hat off to you for your powers of observation and deduction.

You’ll remember from a previous post that a common programming error is to use the assignment operator, =, when you meant to use the equality operator, ==. You’ll also recall that when you use the assignment operator in a condition, it always evaluates as the value of the assignment. If you look closely at line 4 you’ll see that’s exactly the mistake that’s been made here. Each time the condition on line 4 is evaluated, rather than being compared to 1, keepGoing will be set to 1. Since an assignment always evaluates as the value of the assignment, the condition will always evaluate as 1. You’ll recall that C interprets any non-zero number as true, so this loop will never end and the printf command will never be reached. If you ever have a programme seem to hang on you and sit there doing nothing, one of the first things to check is that you haven’t made this sort of error in your loops.

Let’s review the parts of our loop in Buzzword. We have:

  • A counter called i, which we declare and initialise on line 50.
  • A condition, on line 52, that is evaluated at the start of each loop to determine if the loop should continue
  • A statement on line 54 that updates the counter.

Now, it so happens that the need for a loop that includes these three things occurs so often in C programmes that there’s another command, called a for loop, which is dedicated to constructing loops of this nature. Let’s update our code to use a for loop instead of a while loop:

The changed code is on lines 50 to 52.

You can see that the for loop is a lot more compact than the equivalent while loop. That’s because all three of the components we identified are included within the parentheses following for, and separated with semicolons:

Note that, like a while loop, the for loop executes the first of these statements, the initialisation statement, once before the start of the loop. The second statement, the condition, is executed each time through the loop before the body is executed. The final statement is executed after the body has been executed. You should also note that there is no semicolon after this third statement.

Try building and running the programme again and you should get exactly the same number of phrases as you did with the while loop.

Notice that with both forms of loop our counter started at zero and we incremented it at the end of the loop. What that means is that once the counter is equivalent to numberOfPhrases we have already displayed enough phrases. That’s why we’re checking that the counter is less than numberOfPhrases(i < numberOfPhrases), not less than or equal to numberOfPhrases: (i <= numberOfPhrases). For that to work, we’d have had to change the declaration and initialisation of i to int i = 1. It’s easy to use the wrong condition for the starting value of your counter, which will mean your loop will execute either one time more than it should or one time fewer. This is known as an off by one error. It’s another thing to check for if your code isn’t behaving as you expect.

At this point I want to address something that might have been bothering you. In a previous post I stressed the importance of giving meaningful names to variables, and yet here I am calling a variable i. Well in this case it’s a valid exception. It’s traditional to use i for counters in loops. These types of variable are sometimes referred to as index variables, which is where the i comes in. You can safely use i as a variable name in this way as experienced programmers will understand, from the context, what it means.

This is all great, and we’ve had fun extracting information from the command line, but so far we are not living up to the promise of the original programme. In the original, the user could decide after each phrase if they wanted another phrase or not. We’ll fix that in the next post.

In the meantime, here’s a challenge for you. There’s yet another type of loop in C, called the do … while loop. It looks like this:

do {
       .
       .
       .
} while (condition);

Here’s how it works. Everything in the braces is executed at least once. At the end of each execution, the condition is tested and, if it’s true, the loop is repeated. One thing to note about this type of loop is that, because the condition comes at the end, not the beginning, it’s terminated with a semi-colon.

Your challenge is to rewrite the programme to use a do … while loop. The solution will be shown in the next post.

 

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: more on decisions and functions

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: command line arguments and decisions

In the previous post in this series, you learned how to read and validate command line arguments. I also left you with a couple of challenges. The first of these was to change the validation code so that, if the programme is run with no arguments, it should default to showing one phrase.

Here’s my solution:

Your solution might not be exactly the same as mine, but as long as your programme behaves in the correct way, that’s fine.

Notice that, now our programme is starting to get a bit larger, I’ve added comments to explain what each section does. If you are intending to share your code with other programmers, or have other programmers collaborate with you on a project, commenting your code is essential. But, even if that isn’t the case, it’s still a good habit to get into. Although you might not need those comments now, when you come back to work on an old piece of code you haven’t looked at for a while, you’ll be glad you made the effort as it will save you a lot of head-scratching and frustration trying to work out why you did things in a certain way.

OK, let’s have a look at what’s going on here. In line 18 I’ve added a new if command that checks to see if argc is equal to 1. Remember that there is always at least one command line argument, which is the path and filename that was entered to run the programme. So if argc == 1 is true, that means the user didn’t enter any additional arguments. If this is the case we simply set the numberOfPhrases to the default value of 1 on line 20.

On line 21 you can see the else command that you are used to, but it’s immediately followed by another if command. The condition in the second if will only get checked if the condition for the first if is false. You can chain any number of if commands together this way:

chaining if statements

So you can see that the logic for our programme is:

  • Check if no arguments have been given (line 18) and use a default value if so (line 20).
  • If some arguments have been given, check that the right number of arguments have been given (line 21) and quit if not (lines 23 and 24).
  • If neither of those things is true, then that means exactly one argument has been given, so get it and attempt to convert it into an integer (lines 27 and 28), quitting if it can’t be converted (lines 32 and 33).

OK let’s check if all this works. First edit your scheme, as you learned in the previous post, so we can switch off the command line argument. Note that you don’t have to remove the command line argument, you can simply uncheck the check box next to it to disable it, then click OK:

Xcode disable command line arguments

Now try building and running your programme. It should detect there are no arguments and set the number of phrases to the default value of 1:

Buzzword default number of phrases for no argument

Now edit the scheme again, make sure that your argument is set to a number other than 1 and re-enable it, before clicking OK. Now build and run again and this time you should see a message confirming that you requested that number of phrases:

Buzzword successfully read command line number

The other part of this challenge was to check that the number of phrases requested fell within a reasonable range, e.g. 1 to 99. At the moment your programme will quite happily accept any integer number between -2,147,483,648 and 2,147,483,647. A negative number or 0 doesn’t make sense and a sufficiently large positive number could crash your programme.

Here’s my solution:

The changes are on lines 30 and 31. Notice that, rather than adding another else if to the chain, I’m hijacking the condition that checks if the number was converted successfully. I’ve introduced a couple of new operators here. The first two, < and >, return true if the left operand is less than the right operand, or if the left operand is greater than the right operand respectively. There are also two associated operators, <= and >=, that return true if the left operand is less than or equal to the right operand, or if the left operand is greater than or equal to the right operand respectively. So the two checks we are making here are to see if the numberOfPhrases is less than 1 or greater than 99.

So what are those funny double vertical lines, ||,  between the conditions? These are yet another operator, called the logical OR operator. There are two logical operators that can be used to combine the conditions in a statement:

  • The OR operator, ||, will return true if either the left operand or right operand is true (or if both operands are true) and false if the left operand and right operand are both false.
  • The AND operator, &&, will return true only if both the left operand and right operand are true, and will return false for all other cases.

There is also a third logical operator called NOT, !, that takes a single operand and will change it’s value from true to false, or from false to true.

It’s common to express logical operations like this in a truth table, which shows the output for all possible combinations of input. Here are the truth tables for these three operators:

a || b (a OR b)

a b output
false false false
false true true
true false true
true true true

a && b (a AND b)

a b output
false false false
false true false
true false false
true true true

!a (NOT a)

a output
false true
true false

An important thing to note about logical operations is that C will be efficient about the way it checks them. So in our statement on line 30, if it discovers that errno == EINVAL is true, it won’t bother to check the other two conditions since it knows that their results are no longer going to make any difference to the result of the whole expression. Can you see why?

An OR operation is true if either of the operands is true, so as soon as any of the conditions in this expression is true, the whole expression must be true. You’d get a similar situation if the expression was something like (errno == EINVAL && numberOfPhrases <1). In this situation, if errno==EINVAL turned out to be false, c wouldn’t bother checking to see if numberOfPhrases was less then 1 because the result is irrelevant at that point – in an AND operation, if either operand is false the whole expression must evaluate to false.

Again, if you attempted this part of the challenge, you probably came up with a different solution to me. As long as your solution results in the correct behaviour, that’s fine. Before we move on, test your programme with:

  • No arguments
  • Too many arguments
  • A single argument that’s a word rather than a number
  • A single argument that’s too small (0 or negative)
  • A single argument that’s too big (100 or higher)
  • A single argument that’s within the correct range (1 to 99)

Check that you get the results you expect for each of these tests. You’ll notice that I didn’t ask you to test just the new checks for range, but all of the previous validation checks too. This is a practice known as regression testing. It checks that changes you’ve made to your programme haven’t introduced new errors into code that was previously working correctly. It’s sensible to get into the habit of doing this whenever you make changes to your code.

I set you a second challenge at the end of the previous post, which was to consider that we have two blocks of code, lines 23 – 24 and lines 32 – 33 that are identical. I asked you to think about whether this was an acceptable situation. If you thought it was acceptable, consider this. We’ve now made some changes to our programme so it only accepts numbers within the range 1 to 99. We should change our usage message to reflect this. Currently though, our usage message is in two different places in our programme. If we change it in one of these places, we have to change it in the other place too. If we forget to make the change in one place, we’ve created a poor user experience. In more extreme cases, not updating duplicate sections of code correctly could introduce errors.

The solution to this is to avoid the situation where you have two or more sections of code that perform an identical function. So what can we do about this? One solution is to rewrite the code in our main function so that the usage message only has to appear in one place. Changing the structure of code so that it results in the same output but does it in a more efficient way is known as refactoring. It’s something we’ll revisit in future posts.

The other approach, and the one we’ll take, is to move the code that’s duplicated into its own function. We can then call that function whenever we need that code to run. (NB there is actually a third way round this problem, which is to use something called macros – this is an advanced topic that we’ll consider in a future post).

The new function will simply display a usage message and then end the programme. Change your programme as follows:

The new/changed lines are 14 and 15, 26, 34 and 56 to 60.

The new function starts at 56. You should give functions names that represent what they do, so a good name for this function is displayUsageAndExit. Note again that I am using camel case for my function names. You don’t have to do this, but whatever style you choose, you should be consistent with it. Note that, like variables, function names can contain only upper and lower case letters, digits and the underscore character. You are not permitted to begin a function name with a digit. Now this function doesn’t need any parameters, so the function name is followed by empty parentheses: displayUsageAndExit(). You’ll remember from our analysis of the main function that the function name is preceded with the return type. Our new function won’t return any value, and to indicate this we use the keyword void.

Again, remember that the body of the function is placed between a pair of braces. Some programmers like to put the opening brace on the same line as the function name, like this:

void displayUsageAndExit() {
   .
   .
   .
}

It doesn’t really matter which style you use, as long as you are consistent with it.

You are already familiar with the printf function on line 58, but note that I’ve now expanded the usage statement to mention the permitted range.

The exit function on line 59 is new. This function is part of the standard library, stdlib. The exit function ends the current programme. It accepts a single parameter, which is a status code it sends the parent process. In other words, exit(EXIT_FAILURE) used in this function is performing a similar role to return EXIT_FAILURE in the main function. So why didn’t we just use return EXIT_FAILURE in this function as well?

You’ll recall that every C programme has a main function and that main is the first function that is called when the programme begins. In other words, main is called by the parent process – which in our case has been either Xcode or Terminal, depending on how we’ve been running the programme. When we use a return statement in main, it returns control to the parent process, effectively ending the programme.

Our function, displayUsageAndExit, is not called by the parent process, it’s called by main, in lines 26 and 34. So if we were to use a return statement in displayUsageAndExit it would return control to main. We’d have displayed our usage message, but our programme would still be running – that’s not what we want at all. So, if you want to end the programme in a function other than main, you need to use the exit function instead.

Before we move on, you might have noticed line 15. This looks identical to the start of our function definition, but it ends with a semicolon instead of a function body. C expects every function to be declared before it is used (in a similar way to how we declare variables before we use them). To declare a function you write the function return type, name and arguments in parentheses, followed by a semicolon. The function declaration can be anywhere in your file, but it must appear before the first call to that function. Practically though, you should group all your function declarations together near the beginning of the file.

OK run your tests again, and you should find the programme behaves identically to the way it did before we created the new function.

In the next post, we’ll finally get round to doing something with that user input.

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: command line arguments and decisions

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: functions and random numbers.

In the previous post you learned how to generate random numbers and how to use these to display a randomly generated string. I also left you with a couple of tricky challenges.

The first was to think of a situation in which you might want your random numbers to always start at the same point in the sequence by using srand with an integer literal rather than with the time function. The answer is when you’re testing your code. If you are trying to remove errors from your code, it’s often useful to be able to test it several times using exactly the same conditions. This way you can be sure that the changes you’ve made have actually fixed the problem, and not that the problem has just been temporarily masked because some values have changed.

The second challenge was to think about why our method of getting random numbers in a particular range will often be biased towards one part of the range. Here’s why. On my machine, RAND_MAX is set to 2,147,483,647. If we divide this by 13 we get 165,191,049.76923076923077. In other words, RAND_MAX is not exactly divisible by the size of our range. The highest multiple of 13 that is less than or equal to RAND_MAX is 2,147,483,637, which leaves a remainder of 10. This means that there is a very tiny bias in favour of numbers 0 to 9 in our range, because those numbers have a 1 in 165,191,050th greater chance of appearing. The larger your range gets, the more bias there is likely to be towards one part of it. For example, if you were choosing random numbers from a range of 100,000, the numbers 0 to 83,646 would have a 1 in 21,475th greater chance of appearing. If you were developing a scientific application that required a high degree of accuracy, you might want to find a solution to this. For the purposes of a game however, and with a range of this magnitude, this bias is so small as to make no appreciable difference.

In the previous post you also learned about functions. So far you’ve called various functions from your programme, but you haven’t seen what a function looks like. Well actually you have. All the code you’ve written so far has been within a special function called main.  It’s special because it is the only function that is required in every single C programme. When a C programme starts it always starts by calling the main function. Let’s have a look at your programme again to see how it’s structured:

The main function begins on line 13. You’ll recall from the previous post that some functions return a value and the value must always be of one type. When we define a function, we start with a keyword to show what type it returns, in the same way as we start variable declarations with a type. You can see from line 13 that the main function returns an integer.

The next part of the function definition is the name of the function, in this case main.

You’ll also recall that, for some functions, we included comma-separated arguments within parentheses. When you define a function you must specify what arguments you expect and what their types are. You can see that the main function accepts two arguments: an integer called argc, and string array called argv. Note that the string array also has a const keyword. You may remember from a previous post that this means the contents of the array may not be changed. If we try to change them from within the function, we’ll get an error. If a function has no arguments, you will still include the parentheses, but they will have nothing within them.

Next we have the body of the function – this is the code that the function executes when it is called. The body of the function is included within a pair of braces. You can see these in lines 14 and 27.

Line 16 of the function is a comment. Comments begin with two forward slashes. This tells C, “everything on this line from this point on is a comment for my benefit, so please ignore it.” Comments are a useful way of reminding yourself, or other people who view your code, what each part of it does, so you should use them liberally. Although this comment is within your function, you can use them anywhere in your file. You can see other examples of comments in lines 1 to 7. The comment on line 16 was placed there by Xcode to show you where to put your own code. You can delete this now.

Lines 17 to 24 are the code that you added in the earlier parts of this tutorial.

Line 26 was also created by Xcode. It’s a return statement. A return statement ends the function and returns control to the code that called it. When a function returns a value, the return statement should end with the value to be returned to the calling code. In this case we are returning the int 0. Zero, in this context, is a way of this function telling the calling code, I’ve finished running and everything is OK.

If you define a function that doesn’t return a value, then a return statement is optional, because your function will also return when it reaches the closing brace, like the one on line 27.

You may remember, when you chose the template for this programme in Xcode, that you selected a Command Line Tool. What is this? Since you own a Mac, you are probably most familiar with programmes that run in a graphical user interface (or GUI). These are programmes that use windows, buttons, text boxes and so on. However, your Mac can also write programmes that run from a command line. To explore what that means we have to venture outside of Xcode for a bit.

First though, you’ll need to find out where Xcode has stored the built version of your programme. First build and run your programme to make sure it is working correctly. Now go to the Project Navigator, if you are not already there, and open the group called Products. You should see a single item within it, called Buzzword. This is your built programme, and this is what Xcode has been rebuilding and running every time you ask it to:

Buzzword executable in Xcode

 

To find out where this built programme has been stored, first click it to select it. Now look at the narrow pane on the far right of the window. This is the Utilities pane.

Utilities paneIf you don’t see this pane, look for the following icon at the top right of the Window:

Xcode utilities icon

If it’s grey, not blue, click it and the Utilities pane will appear.

At the top of the Utilities pane, click the icon on the left that looks like a document page with the top-right corner turned down. This shows the File Inspector:

Xcode file inspector

In the File Inspector, Full Path shows where the built programme is located on your hard drive. The path on your machine will be different to the one shown here. Click and drag to select the path – make sure you get all of it. Then, while it is highlighted in blue, right click it and select Copy.

To run this programme outside of Xcode, we need to use an application called Terminal. The easiest way to find this is type it into Spotlight Search (click the little magnifying glass icon in the top right of your screen, type Terminal, and select it from the list). You should then see a window that looks similar to this, except the information at the top will be different for you:

Terminal

Now click on the hollow square in this window so that it goes solid, and type cd “ (that’s the letters c and d followed by a space then an opening quote mark). Now right click at the end of what you’ve typed and select Paste. The path you copied earlier should be pasted in. Now use the backspace key on your keyboard to carefully delete the word Buzzword from the end of the path. Don’t delete the forward slash that comes just before it. Now type  (that’s a closing quote mark). All being well, you should have something like this:

Terminal cd command

What you have constructed here is a cd command, which is short for change directory (directory is another name for a folder). Press the enter key on your keyboard, and you should see something like this:

Terminal after cd command

What you have done is made the folder (or directory) containing your built programme be your current folder. Now you are at the correct location, you can run your programme. Enter ./Buzzword so that your Terminal window looks like this:

Terminal Buzzword command

Although the programme is just called Buzzword, the ./ at the beginning is a way of telling Terminal, the programme I want to run is located in the current folder. Now hit return and you should see something like:Running Buzzword in Terminal:

Congratulations, you’ve just run your first programme outside of Xcode. We’re going to go back to Xcode for a little bit now, but keep the Terminal window open as we will be coming back to it later.

Back in Xcode, select your main.c file in the Project Navigator. Now you already know that some functions take arguments, which are included in the parentheses after the function name and separated by commas if there’s more than one. You’ve already seen examples of this when you’ve used the printf, srand and time functions. You can also see that the main function in your programme accepts two arguments, argc and argv. What you might be wondering is, if main is the first function to be called in every C programme, where do those arguments come from? The answer is, they come from the user.

When you typed Buzzword into terminal to run your programme, you could have also followed it with one or more arguments separated by spaces, e.g.

./Buzzword argument1 argument2 argument3

What C does when it finds these arguments is count them. It then puts that number into argc (which you can probably now guess stands for argument count). Then it takes each argument and puts them, in order, into the elements of the array argv (which stands for argument vector). When your programme starts, it can then access the argument count and argument vector and use them as it needs to. This is one way of getting user input into a command line programme.

To see how this works, we’ll modify our programme so that it accepts a single argument. This will be an integer representing the number of phrases that we want displayed.

The first thing to do with any kind of user input to your programme is to validate it. Otherwise users who are not sure what they are doing (or who are just plain malicious), could break your programme with nonsensical input.

The first bit of validation we will do is to check that we have received the right number of arguments.  Change your programme so it looks like this:

The new code is in lines 15 to 18, and there’s a change to line 29. The if command in line 15 is a very important part of the C language. Up to now our programme has executed each statement in order, starting from the top of the main function and working towards the bottom. Sometimes though we might want to execute some code only under certain conditions. This is where the if command comes in. The if command will evaluate whether an expression is true or false and then only execute some code if the expression is true.

The expression to be evaluated is placed in parentheses after the if command. This is known as the condition. So in this case, the expression we are evaluating is argc != 2. Notice that we use the argument name in exactly the same way we would use a normal variable. This is the first time you have encountered the != operator. It means not equal. In other words, we are checking to see if argc is not equal to 2. So this expression will evaluate as true if argc is equal to any other value than 2 and it will evaluate as false only if argc is equal to 2.

Now at this point you might be thinking, “hold on, I thought we wanted just one argument – the number of phrases that the user wants displayed – so why are we looking for two?”. Well, when C collects all the arguments, it also includes whatever you typed to start the programme. So every C programme will always have at least one argument, which in our case is “./Buzzword”. Any additional arguments will start from the second element of argv. This is why we are looking for a count of 2 and not 1.

OK what happens if the condition is true? In this case C will execute the body of the if statement, which is all of the statements within the braces that follow the if command. In our case, this will be the statements on lines 16 and 17. Note that the closing brace is not followed by a semi-colon, but the statements within the braces are.

If the user has entered the wrong number of arguments, our programme will use a printf function to display a useful reminder of how it should be used. This is followed by a return statement. This immediately ends the programme. Notice that we have returned the value EXIT_FAILURE and the return value at the end of the function has been changed from 0 to EXIT_SUCCESS. You’ll recall that returning a code of 0 indicates that the programme ran successfully and terminated normally. In this case, because the programme has detected the wrong number of arguments and is ending abnormally, we return a non-zero value. C has two special values defined, called EXIT_FAILURE and EXIT_SUCCESS. When the code is built, these will be replaced with values that are appropriate for the system the code is being built for. Using them helps to make our code more portable between systems and to future proof it to some extent.

If the condition is not true then the body of the if, i.e. all of the code between the braces (lines 16 and 17), will be ignored and execution will continue from the first statement following the closing brace (i.e. line 20).

Let’s see how this works. Rebuild the programme by selecting the Product menu and then Build. This is how you build a programme if you don’t also want to run it immediately after the build. You can also use the short cut – hold down the cmd key and press B. Now return to the Terminal window. If you’ve closed it, just repeat the instructions from earlier in this post to reopen it and make the build folder be the current folder.

Now try entering ./Buzzword without any arguments. This time you should see the following helpful message:

Terminal with incorrect number of arguments

Now try it again, but with two arguments, e.g. ./Buzzword 1 2 (note that arguments on the command line are separated with spaces, not commas and you don’t put parentheses around them like you would in a function call). You will get the same message.

Finally try it with just one argument, e.g. ./Buzzword 1 and this time you will be rewarded with a random phrase, as before. Note that all we are doing at the moment is checking for the right number of arguments, we aren’t doing anything with the argument we receive. In fact it doesn’t matter at the moment whether your argument is 1, 99, or bananas, your programme will quite happily give you a phrase in response to any of them, but it will only give one phrase, regardless of what number you use.

We’ll fix that in a minute, but for now let’s fix something else that’s a bit annoying – having to go out to Terminal every time you want to test your programme with command line arguments. Well Xcode has a way round that too. You can close the terminal window now and return to Xcode.

Normally Xcode will run your programme without any arguments. Try it now by hitting the run button and you’ll see the now familiar complaint from your programme when it doesn’t receive the right number of arguments. Let’s fix that now. Go to the Product menu and select Scheme then Edit Scheme…. You should see a window that looks like this:

xcode edit scheme

If it looks a little different, check that Run Buzzword is selected on the left hand side.

Each time you build in Xcode, you build for a specific target or targets. A target is a version of the product intended for a particular system or range of systems. Because you selected a particular template when you started this project, Xcode created a default target for you.

Xcode also has the concept of schemes. A scheme specifies the target or targets to build for,  a build configuration and a set of tests to run. You haven’t yet looked at how to make changes to targets or configurations or how to set up tests. You’ll look at all of these in a future post. Xcode also creates a default scheme for you. You’re going to edit that scheme now to supply a command line argument when you run the application.

Click the + button at the bottom of the section marked Arguments Passed on Launch.  In the text box that appears, type the number 1. The Edit Scheme window should now look like this:

Xcode add command line argument

Click OK. Now try building and running again. This time the programme will run successfully and show you a random phrase again.

Now that we are able to supply an argument from within Xcode, let’s turn our attention back to verifying the user’s input. So far we have checked that the programme received exactly one argument, but at the moment that argument can be anything. We need to make sure it’s a number.

Change your programme to look this this:

The new/changed code is on lines 12 and 16 to 31. When you enter this code, Xcode will show you two symbols in the margin, like this:

Xcode errors

Ignore these for now – we will revisit them later.

The first thing to notice is that our if statement has now become a bit more involved. You’ll recall that the body of an if statement is only executed if the condition is true. In our case, the code is only executed if argc does not equal 2. But we can also include some code that will only be executed if the condition is false. To do this, we add the keyword else after our first set of braces, then we add a second set of braces with the code that is to be executed if the condition is false. In our case, if the condition is false, i.e. argc does equal 2, then the code in lines 23 to 28 will be executed. This is shown in the diagram:

if else decision

You’ll recall from the earlier discussion that the second argument to main is an array of string pointers and that each element points to one of the arguments supplied on the command line. We can obtain the string representing any of the arguments by specifying the relevant array subscript. Note, in line 23, that we get the second element of the array, [1], and remember that this is because the first element, [0], points to the text entered to start the programme.

Because all the command line arguments are stored as strings, we need to convert the argument to an integer before we can do anything useful with it. We can convert a string to an integer using the strtol function. This is short for ‘string to long’. Long is another type of integer that supports larger numbers than a standard int. The maximum number an integer variable can hold depends on how many bits (binary digits) it has. The size of these variables depends on which system your code is compiled to run on, but generally a long has more bits than an int. For example, an int might have 32 bits, which would mean it could store numbers between -2,147,483,648 and 2,147,483,647, while a long might have 64 bits, which would mean it could store numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

Because we want an int rather than a long, we also use a typecast, (int), to treat the result as if it were an int. You might be wondering why we don’t just use a typecast directly on the string to convert it to an integer. The reason is because type casting does not actually change a value, it simply asks C to reinterpret it as another type.. When we use a typecast to view a long as if it were an int we know that c is always going to be able to complete the operation because it is treating one number as another type of number. The worst thing that will happen is that some information will be lost  because the new int might not be big enough to hold the old number, but the programme won’t crash. Remember that a string array doesn’t hold the actual text, it holds pointers to the text in memory, and a pointer is a large number. So if we try to us a typecast on a string pointer, C assumes we simply want to treat the pointer as if it was a int – so we’ll end up with some sort of number, but not the one that we intended to get.

That’s where the strtol function comes in. It will try to make sense of the string as a number. If it can it will give you the number. If it can’t, it won’t crash, it will simply let you know – “Hey, I tried to make this happen, but it just didn’t work out. OK?” How does it do this? The function strtol is designed to work with a special error handling library called errno (short for error number). You imported this library on line 12. This library creates a special variable, also called errno. When strtol is called, it changes the value in errno depending on how successful the conversion was. If the string could not be converted, errno will contain a value defined as EINVAL. So on line 25 we can check to see if errno is equal to this value. If it is, we know that the user has entered a non-sensensical argument and we can end the programme and show them the usage message.

You might be wondering about the second and third parameters for strtol. The second parameter is an optional string pointer. If this parameter is present and an error occurs, strtol will set this pointer to point to the first invalid character in the string supplied as the first parameter. This is useful if you need to do more advanced error handling, but is not required for our purposes, so we set it to NULL. The third parameter indicates what base the number should be interpreted as. In computing we often use a number base other than 10, most predominantly base 2 (binary), base 8 (octal) and base 16 (hexadecimal). We won’t torture our users by requiring them to use anything other than decimal, so we’ve set the base to 10.

Notice that when we checked for EINVAL on line 25, the equality operator we use is not a single = sign, but a double ==. A single = sign means, I want whatever is on the left of the operator to be equal to what is on the right of the operator. If you used a single = sign here, so that the condition was if(errno = EINVAL), what do you think would happen?

C would interpret the bit in the brackets as meaning, “I want errno to be set equal to EINVAL”. This is exactly what it would do. Not only that, but an assignment always evaluates as the value of the assignment. C treats zero as being equivalent to false and any non-zero number as being equivalent to true, so whether the code between the first set of braces would be executed, would depend on the value of EINVAL. You can see how easy it is to break your programme by using = when you meant to use ==. Believe me when I say you will do this a lot while you are learning, and you will continue to do it a lot, even when you are experienced, so it’s one of the first things to check for when your programme doesn’t work as you expect.

Fortunately for us, Xcode is very helpful with things like this. In line 25, change the == (equality) operator to an = (assignment) operator and see what happens. Xcode will add another one of those funny symbols to the margin:

xcode equality vs assignment error

What is this? Whenever you see a yellow triangle in the margin, it’s Xcode warning you that you might be trying to do something that could result in your programme not working as you expect. Note the use of the words ‘might’ and ‘could’ in that sentence. A warning doesn’t necessarily mean your programme has errors. It’s just Xcode telling you to be wary and double check your code. By default, Xcode will still happily compile and run your code, even if it contains warnings.

You might also see red hexagons in the margin, like this:

xcode error

This indicates an error. This symbol means, “there’s something wrong with this code – you need to fix it”. Unlike warnings, errors will stop Xcode from building your code. If you try to build a programme with errors in it, you’ll get a “Build Failed!” message.

So how do you know what the warning or error is? Go back to line 25 and click once on the warning symbol in the margin. You should now see that Xcode has placed a helpful message next to the line:

Xcode warning message

Xcode is helpfully telling us, “Hey, you’ve used an assignment operator in a condition – are you sure that’s what you want buddy?”. Clicking on the warning or error symbol is a quick way of checking what a particular issue is, but what if you had a lot of errors and warnings and you wanted to work through fixing them one by one? It’s time to introduce you to another navigator – the Issue Navigator. In the Navigator pane on the left side of the window, click the icon at the top that looks like the warning symbol – an exclamation point in a triangle. Your Navigator pane should now look like this:

Xcode issue navigator

This lists all the warnings and errors in your programme, sorted by file. You can see that the top warning is the one about our use of an assignment operator in a condition. Click once on this. Xcode will helpfully take you to the right place in the file and will also pop up a menu with some suggested actions to address the warning:

xcode warning actions

The first of these, “Place parentheses around the assignment to silence this warning” would be something we’d do if it had been our intention to use an assignment operator here. In this case, we want to use the second suggestion, “Use ‘==’ to turn this assignment into an equality comparison”. Click this option once now. Xcode will preview the change for you – you can still change your mind at this point and select another option. In this case though, we’re happy that this is the change we want. Double-click the option and Xcode will make the change and the warning will disappear. Hopefully by now, you’re starting to appreciate some of the additional benefits that working in an IDE like Xcode gives you over a simple text editor.

While we’re busy fixing warnings and errors, let’s turn our attention back to line 23. In this statement we are using the strtol function to convert our string into a number and we’re then assigning our number to an int variable called numberOfPhrases. If you look in the Issue Navigator, you can see that Xcode is warning us that the variable numberOfPhrases is unused. Well that’s strange, because if you look down at line 31, you can see we have used numberOfPhrases as an argument to a printf function. To complicate matters further, there’s an error on that line too. If you look in the Issue Navigator, you can see that the error is that we’ve used an undeclared identifier called numberOfPhrases. But we have declared it – back on line 23! What’s going on? Has Xcode lost the plot?

This is another issue you will frequently encounter as you are developing your programming skills. The problem is one of variable scope. Scope is an important concept in c. Imagine a theme park called “Fun Days” that gives you a choice for how you buy your tickets. You can go into the theme park and you can buy a ticket for an individual ride. If you just want to go on the Big Dipper, you can buy a ticket for that ride, but the ticket will only be valid for that ride. If you try to use that ticket to go on the the Crazy Swings ride, the attendant will say “Sorry – this ticket isn’t valid here.”

variable scope 1

However, I can choose instead to buy a “Fun Days” ticket at the gate that will let me into any ride within the park. Now the attendants at both the Big Dipper and the Crazy Swings rides will quite happily accept that ticket.

variable scope 2

You could say that the ‘scope’ of the Big Dipper ticket is limited to the the Big Dipper ride, while the ‘scope’ of the Fun Days ticket encompasses the whole theme park, which includes both the Big Dipper and Crazy Swings rides.

In C, whenever you use braces, {}, the code within the braces becomes an entity in its own right. So consider your main function as being somewhat like the Fun Days theme park, and consider the code within the braces following your else command as being like the Big Dipper ride. When you declare a variable inside the braces following your else command, that’s like buying a ticket that’s just for the Big Dipper ride. While you’re within those braces it’s valid, but try to use it outside of the braces and it won’t be valid.variable scope 3

So how do we get round this? Well, ideally we want a ticket/variable that’s valid for the Big Dipper ride/else braces but can also be used on the Crazy Swings/printf function outside the braces. The solution for the rides is to trade up to a Fun Days ticket which you buy at the gate. We’re going to adopt the same solution for the variable. By declaring it within the main body of our function, it will be available throughout the function, not just within the else braces.

On line 16 you’ll see I’ve included a declaration of the numberOfPhrases variable, but I’ve put two forward slashes at the start of the line. You’ll recall from earlier in this post that this turns the line into a comment. Previously we’ve used comments to simply add useful information to the file. Another common use of comments is to temporarily disable lines of code. In a later post we’ll explore why this is useful in testing. For now, delete the backslashes so the statement is enabled. You should now see that the error on line 31 has gone. but the error on line 23 is still there. Why is this?

Another aspect of scope is that you are allowed to redefine a variable, as long as the scope for the redefined variable is different from the scope of the original variable. When you do this, the new version of the variable hides the previous version while the new version is within scope. The following example shows how this works:

hidden variables

So that’s what’s happening with our code. Because we still have the variable declaration in line 23, we are effectively defining a new version of numberOfPhrases that will only be visible within the else braces. This is not what we want, so fix it by changing line 23 to read:

This should make the final warning disappear. Don’t worry if you’re still struggling to get your head around the concept of scope. It’s one of the trickier concepts in programming and it will come with practice as you analyse more code.

Now let’s check if our new validation code is working. Follow the earlier instructions to edit the scheme. Double click the argument to edit it and change it to something like “bananas”. Click OK then build and run the programme and you should see the usage notice.

Go back and edit the scheme again, and change the argument to an integer number, e.g. 99. Now when you click OK then build and run, you should see something like this:

Buzzword successfully read command line number

Great work. In the next post you’ll continue to make improvements to your programme. In the meantime, here’s a couple of challenges for you. It would be useful if the argument was optional and defaulted to a value of 1 if it was missing. How would you modify the code to allow for that possibility? While you’re at it, you might also want to set a sensible and reasonable lower and upper limit, say 1 to 99, on the number of phrases that can be generated. Here’s a hint. There are a few comparison operators we haven’t used yet that you might find useful for this exercise. They are: <, <=, > and >=. You should be able to work out what they do just by looking at them. Experiment, and we’ll explore them further in the next post.

For your second challenge, you might have noticed that we now have two bits of code, lines 19-20 and lines 26-27 that do the exact same thing, but at different places in your programme. Is this an acceptable situation? If you don’t think it’s acceptable, what might we be able to do about it? Solutions will be shown in the next post.

 

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: index

This index explains what you’ll learn in each part of OS X games from the ground up. It also includes download links for the starter files for each part of the project. This makes it easier for you to start, or restart, at a particular point without having to work through from the beginning. To start at any post other than the beginning, download the starter files from the link that is immediately before the post you want to start from.

First steps

  • Introduction
  • Source code for the first programme to be converted: BUZZWORD.BAS
  • Constructing a simple flowchart
  • Introduction to the C language
  • Introduction to Xcode
  • Creating a Command Line Tool in Xcode
  • The Xcode Project Navigator
  • Building and running the Hello World programme
  • The Xcode Debug pane

Starter files from end of First steps: first steps

Your first programme

  • Opening an existing project with Xcode
  • The printf function
  • Escape sequences
  • Terminating C statements with a semi-colon
  • The Xcode Log Navigator

Starter files from end of Your first programme: your first programme

Variables

  • What is a variable?
  • The C stack
  • Variable declarations
  • The int and float types
  • Format specifiers
  • The value of uninitialised variables
  • Initialising variables
  • Simple operators: addition, +, subtraction, -, multiplication, *,  and division, /
  • Operator precedence and order of associativity
  • Using parentheses in expressions
  • The char type
  • Introduction to arrays
  • Declaring an array of ints
  • Initialising an int element in an array
  • The numbering of array elements
  • Declaring and initialising an array of ints in a single statement
  • Declaring and initialising an array of chars
  • Referencing individual elements of a char array
  • Declaring and initialising a string
  • The null character
  • String and integer literals

Starter files from the end of Variables: variables

More fun with variables and arrays 

  • Naming variables
  • Declaring an array of strings
  • Initialising an array of strings
  • Introduction to pointers
  • The const keyword

Starter files from the end of More fun with variables and arrays: more fun with variables and arrays

Functions and random numbers

  • Introduction to functions
  • Introduction to function libraries
  • Including function libraries
  • rand() and RAND_MAX
  • Getting a random number within a particular range
  • Rules for variable names
  • Using return values from functions
  • Function arguments and functions without arguments
  • The modulus operator
  • What are pseudo-random numbers?
  • The srand function
  • The time function
  • Using the date and time to seed the random number generator
  • NULL and null pointers
  • Introduction to typecasting

Starter files from the end of Functions and random numbers: functions and random numbers

Command line arguments and decisions

  • Using integer literals with srand for testing
  • Random number bias
  • The parts of a function
  • Command line arguments
  • Running command line tools from Terminal
  • Supplying command line arguments within Xcode
  • Decisions with if and if … else
  • Xcode warnings and errors
  • The Issue Navigator
  • The strtol function
  • The errno library
  • Variable scope

Starter files from the end of Command line arguments and decisions: command line arguments and decisions

More on decisions and functions

  • Using comments
  • Chaining decisions with if … else if … else ….
  • Enabling/disabling command line arguments within Xcode
  • <, <=, >, >= operators
  • Logical operators: ||, && and !
  • Truth tables
  • Evaluation of conditions with logical operators
  • Regression testing
  • Creating a function
  • The void keyword
  • The exit function
  • Difference between return statement in main and return statement in other functions

Starter files from the end of More on decisions and functions: more on decisions and functions

Loops

  • The while loop
  • The increment and decrement operators, ++ &  --
  • Prefix and postfix modes for increment and decrement operators
  • Programming errors leading to infinite loops
  • The for loop
  • Off by one errors
  • Index variables

Starter files from the end of Loops: loops

User input

  • The do … while loop
  • Removing command line arguments in Xcode
  • The scanf function
  • The reference operator, &
  • Showing/hiding the variables view in Xcode
  • Making scanf ignore white space
  • The fgets function
  • The sizeof() operator
  • The sscanf function

Starter files from the end of User input: user input

Challenge project 1

  • Source code for the programme to be converted: ACEYDUCY.BAS
  • Using Quick Help in Xcode

Solution to challenge project 1

  • Example Acey Ducey programme
  • Removing parameters from the main function
  • Using functions to separate programmes to structure your programme
  • Passing arguments by value, explicit reference and implicit reference
  • Comparing strings with the strcmp and strncmp functions
  • Evaluating strings based on their text encoding
  • Scanning strings with for loops
  • The tolower function
  • Creating reusable functions
  • Single statement loops and decisions
  • Swapping variables
  • The sprintf function
  • The switch command
  • Assigning strings with the strcpy function
  • Using the break command with switch
  • How the stack works
  • Why you shouldn’t return pointers to local variables
  • Dangling pointers
  • Separating model from interface
  • The stdbool library
  • The bool type
  • True and false values
  • The compound assignment operators: +=,  -=, *=, /= and %=

Project files for the solution: challenge project 1

Built version of the solution: Acey Ducey

Volume 2 of this tutorial series is now available.

Posted in Games, Programming Tutorials | Tagged , , , , , , | 2 Comments

OS X games from the ground up: functions and random numbers

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: more fun with variables and arrays

In the previous post you learned what pointers are and how to use them to create an array of strings. I also left you with a challenge. The challenge was to display the phrase “flexible cognitive algorithm” using the string arrays you created in the previous post. If you completed the challenge successfully, your code should now look similar to this:

When you run this programme you should see this output:

String array challenge

Before we carry on building our programme we need to introduce an important new concept: functions. A function is some code that another part of the programme can ask to do a particular job.

You’ve already seen one example of a function, printf. The printf function displays information on the standard output device. When we’re running the programme within Xcode, the standard output goes to both the debug pane at the bottom of the window and the log (which we can view in the Log Navigator).

We get a function to do some work for us by putting its name into the programme at the point we want to use it. The name is followed by parentheses and the parentheses include any parameters (or arguments) that we want to send to the function, separated by commas. This is known as calling a function.

Some functions, like printf, simply do their job and then return control to the code that called them. Other functions do their job and then return a value to the code that called them. Like variables, functions that return values always return values of a particular type, such as int, float or char.

In a later post you’ll learn how to write your own functions. C also comes with lots of ready made functions, of which printf is one.

These functions are organised into logical groups, called libraries.  Whenever you want to use a function from a particular library, you have to let c know. If you look towards the top of your programme you’ll see this line:

This line tells C that we want to make use of a library called stdio, which contains standard input/output functions like printf.

Why do you need to know all this now? Because we’re about to introduce a new function that will help us construct random phrases from our word lists. But first, let’s have a look at the original BASIC programme and see how it handles the task:

You’ve seen PRINT used previously to display string literals. Like c’s printf, BASIC’s PRINT can also display the values held in variables. You should recognise A$ as being the  name of the array that was used to hold all the words. The bracketed material that comes after it is generating a subscript at random. Let’s break it down to see how it works.

BASIC also has functions. One of these is RND(). RND(1) generates a random number between 0 and 1. However there are 13 words in each list, so we really need this number to be in the range 1 to 13.  Multiplying the random number by 13 and adding 1 will give us this, so this is achieved with 13 * RND(1) + 1. However, the resulting number is a floating point number, and array subscripts are always integers. INT(x)  is another function that will drop any fractional part of x to give us an integer, so INT(13*RND(1)+1) will give us a random integer subscript between 1 and 13.

In the second and third statements we add a larger number because the second and third lists of words start later in the array.

Don’t be confused by the semi-colons in these statements. They are not used for terminating the statement, as they are in C. In BASIC they are used to chain together items to be displayed. A semi-colon in a BASIC PRINT command means “put the next thing to be displayed immediately after the last thing I displayed (i.e. don’t go to a new line)”.

So how do we get random numbers in C? We use the function rand(). This is an example of a function that returns a value. Wheres the BASIC function RND(1) generates a random floating point number between 0 and 1, C’s rand() generates a random integer number between 0 and a maximum number called RAND_MAX. The actual value of RAND_MAX will depend on the machine you are running your programme on. However, we don’t need to know what this number is to get the random number into the correct range. We can do this by dividing the random number by the size of our range and then using the remainder. This is achieved with the following statement:

This statement has introduced you to four new things:

1) Notice how I’ve named the variable. Why didn’t I just call it random number? Well spaces aren’t allowed in variable names. In fact the only characters you can use are the lower case letters a to z, the upper case letters A to Z, the underscore character, _, and the digits 0 to 9 (but digits are not allowed as the first character of a variable name). So, randomNumber, random_number, and random13 would all be valid variable names, but random number, 13random, and random*number would cause errors in your programme. The style I’ve used, where an upper case letter is used to denote the start of each word other than the first, is called camel case. It doesn’t really matter what style you use, as long as you are consistent.

2) When a function returns a value, we can use it wherever we would normally use a literal or a variable of the same type that the function returns.

3) Notice that the rand() function takes no arguments, but we still have to include the parentheses.

4) I’ve used an operator you haven’t seen yet. The symbol % is called the modulus operator and it returns the remainder when the first argument is divided by the second argument.

If you were to try and use this statement in your programme right now, it would throw up an error. This is because, like printf, rand is part of a library and we first need to tell C that we want to use that library.

Below the line that includes the stdio library, add the following line:

This tells C we want to use the c standard library, which includes the rand function.

Now we can add the code to display our randomised phrase. Replace the printf statement you created for the challenge earlier, so that your code looks something like this:

Now build and run your programme. You should see something like this:

random phrases output

Great. You finally have something approaching a functional version of the original programme. That’s an achievement worth celebrating, so let’s run it again. And again. And one more time for good measure. Notice anything odd? Yes, you’re getting exactly the same phrase each time you run the programme. What’s up?

Well the random numbers generated by c are not truly random. It uses a clever algorithm to generate a fixed series of numbers that appear random. These are known as pseudo-random numbers. The problem is, each time you start your programme it starts generating the numbers from the beginning of this series, so you always get the same result.

Fortunately, C provides us with a way round this by using another function, srand(x). This does something called seeding the random number generator. The number x that you give to srand will determine where in the sequence the pseudo-random number generator begins. Let’s try it out. Add this statement just before the line containing the printf command that displays your random phrase:

Now try building and running your programme. This time you should see a completely different phrase. Ok try running it again. And again. Hmm – it seems like we still have exactly the same problem. What we really need is a way to give srand a random number, so it always starts from a different point in the sequence. At this point, stop and think about why we can’t use rand to generate a random number for srand.

The answer of course, is that rand will always generate the same number, so srand will always set the random number generation to the same point. It seems like a bit of a Catch-22 situation. Fortunately there is a way we can get a value which is going to be different each time we run the programme. Can you think what this might be?

The answer is the current date and time, which is going to be different each time we run the programme. You might be wondering how we use two different things – the date and the current time – to generate a single number for srand. Luckily for us, C stores the current date and time as a single number that represents the number of seconds that have elapsed since Midnight UTC on January 1st 1970. 

We can get this number using another function: time(). This comes from yet another library called time, so add the following line below the one that includes stdlib:

Now replace the current srand statement with the following one:

There are a couple of things here that will be new to you:

1) We’ve given time an argument of NULL. This is not the same as the null character, \0, that you looked at when we were discussing strings. The time function has an optional parameter, which is a pointer to an object that we want to store the current time in. When a pointer is not used, as in this example, we can set its value to NULL. This indicates to C that the pointer is not currently pointing to anything useful.

2) You are probably wondering what the (uint) bit is. You’ll recall from earlier that all functions that return a value must return a particular type of value. The time function returns a type called time_t. This is also an integer value, but it can be a much larger value than a standard int. The function srand though, wants its argument to be the type uint, which is short for unsigned integer. This is similar to an int, but it only allows positive numbers, whereas int allows both positive and negative numbers. When we have this sort of situation in C, we can use a typecast to change the value from one type to another. To do this we put the desired type in parentheses to the left of the argument. So here we are saying to C, “I know what I’m giving you isn’t a uint, but could you please treat it like it is a uint – thanks very much”.

Now try to build and run your programme again. You should get a different phrase. Run it one more time and the phrase should be different yet again. Now run it once more for good measure – again you should get a different phrase.

In the next post we’ll see how we can get our programme to print multiple phrases in one run. In the meantime, here’s a couple of tricky challenges for you:

1) Normally, when you are creating games in C, you will want to use srand with the time function so that the player gets a different game each time they play. However, while you are developing the game, you might sometimes want to replace time with an integer literal. Can you think why?

2) The method we are using to get the random number into a certain range will more often than not be slightly biased towards one part of the range. Why might this be?

The answers will be given in the next post.

 

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: more fun with variables and arrays

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: variables

In the previous post in this series, you saw how to use variables to store information in your programme. You also saw how to use arrays to store a collection of variables. At the end of that post I left you with a challenge. The first part of challenge was to display the phrase “10 green bottles hanging on the wall”, but to store the number 10 and the word ‘green’ in variables. If you managed to complete the exercise successfully, you would have ended up with something like this (of course your variables may have different names to mine):

When you build and run this, you should see the game instructions you added in an earlier post, followed by this:

green bottles exercise 1

The second part of the exercise was to change the phrase to “9 blue bottles hanging on the wall” by changing the values you use to initialise the variables. This will have made your code look something like this:

Which will display:

green bottles exercise 2

Now that we have a reasonable command of variables and arrays, let’s think how these might be useful to us for storing the list of words.

If we refer back to the original BASIC programme, we see code that looks like this:

What’s happening here? Line 90 is actually doing something you’ve already seen in C. It is creating an array with 40 elements. In BASIC, you dimension an array when you create it, so DIM is short for dimension.

A$ is the name of the array. String variables in BASIC always end with $. An important thing to note here is that the name of the array in the original BASIC programme is just a single letter. This was a common practice at the time this programme was written because some BASIC dialects only supported single letter variable names. C suffers no such restriction, so you should always make your variable names as descriptive as possible, while also keeping them succinct. For example, calling a variable s doesn’t really tell you what the variable is for, whereas calling a variable score gives you a good idea what it does.

Lines 200 to 290 contain all the words for the programme. At present these are stored as string literals, but the programme needs to put them into the array for them to be useful. In BASIC, information can be embedded in the programme using the command DATA. When the programme needs to make use of this data it can read it into a variable using the command READ. The first READ command will read the first piece of data stored, the second will read the second and so on.

Line 100 is an example of a loop. This repeats this line of code 39 times, and for each time it repeats, it reads another word into an element of the A$ array. When this loop finishes, all the words embedded in the DATA lines will have been stored in the array A$. You’ll learn more about loops in a future post.

So in C we’ve seen how to create a single string. For example, we could create a string with the first word, “ability”, with the following line of code:

But how do we create an array of strings? We could declare an array to hold four words like this:

You’ll notice this looks very similar to the way you declared a character array. The difference is that there is now an asterisk between the data type and the name of the array.  We could now initialise the elements of the array like this:

Here’s a challenge for you. With our previous array examples we’ve been able to declare and initialise the array at the same time. This is also possible with string arrays. Have a go at doing this before you read on, then click below to see the solution.

So what does the asterisk mean? We’ve already established that in c when you declare and initialise a simple variable, some memory is set aside to hold the value. When we want to access that memory we use the name of the variable to reference it. Sometimes though, it’s helpful to be able to reference the memory location (or address) of some data directly. We do this using something called a pointer. A pointer is simply a type of variable that holds the address of some data. We use the asterisk to say that we want a pointer rather than a simple variable. So when our line of code above is executed, what we get is something like this:

string array storage

Each of our strings is stored in memory, one after the other. You’ll recall that each string is terminated with a null character (represented by the escape sequence \0). Our array then consists of a four pointers, and each pointer contains the address in memory of the first character of the associated string. You could say that each element of the array points to its string in memory.

We can use pointers in the same way we used simple variables. So if we wanted to display the second word we could do this with:

OK, let’s set up our word lists. Although the original BASIC programme placed all the words into a single array, we will place the words into three arrays, for the first adjective words, second adjective words, and noun words respectively. Modify your code so it looks like this:

You’ll notice I’ve added a new keyword, const, to the start of the declaration. This is short for constant, and it tells C that these arrays will not change once they’ve been initialised. When you have  variables or arrays that should remain constant, it’s always a good idea to use the const keyword, because the compiler will show an error message if you try to make changes to those values. This will help you keep errors out of your programmes.

In the next part of this series you will see how to pick words at random from each list and display them. Until then, here’s a challenge. Display the phrase “flexible cognitive algorithm” by displaying the correct element from each array. Put a new line at the start and end of the phrase and separate each word with a space.

The solution will be shown in the next post.

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: variables

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: your first programme

In the previous post you began constructing your first c programme by using printf to display information to the user. So far we’ve just been showing static information. In this programme though, we also need to create and store information dynamically. For example, we will need somewhere to store the words that we choose from each list.

We can do this in C using variables. A variable is a little chunk of memory that’s been set aside to store a value. Unlike the static information we’ve been looking at so far, the value stored in a variable can, as the name suggests, vary. So how do we know which bit of memory to put our variables in? Well fortunately we don’t have to worry about that level of detail – we just give each variable a unique name to identify it and C takes care of the rest.

Think of C’s role in variable management as being somewhat like a cloakroom or coat check attendant. When you hand over your coat, you neither know nor care which rail or hanger your coat is stored on – that’s the attendant’s job. All you want to be sure of is that, when you hand over the ticket, you get back your coat and not some random coat left by another person.

In C, the spare memory (which is known as the stack) is like the cloakroom, the information you store there is like your coat and the name you give to the variable so it can be identified is like the ticket. So let’s say you want to store the number 73, you might say to C: “Please hang this number up somewhere safe and give it the name ‘score’. ” Later on when you want to add some points to your score, you’ll say: “I’d like the number I left you with the name ‘score’ please”. C then hands it back to you so you can add some points to it, then you hand it back over until you need it again.

Now, in many cloakrooms you can leave different types of items, such as coats, umbrellas, hats and bags. The attendant needs to know which item you want to leave because there is a different charge for each item type. Well the same is true when storing variables with C. We need to tell C what type of information we are storing – for example is it a whole number, a number with a fractional part, some text etc.? And just like the cloakroom attendant needs to know the type so he knows what to charge, C needs to know the type because each type requires a different amount of memory.

So how does this work in practice? Well let’s take our score example. We know we only want to store whole numbers, so we would create this variable with the following statement:

This is called a variable declaration. The int bit tells C that we want to store a whole number. Int is short for integer, which is the mathematical term for a number without a fractional part, e.g. 73. We’d use a different type here if we wanted to store a different sort of number, for example float for a floating point number (a number with a fractional part). The second part, score, is the name we want to use to identify the variable. Notice that we haven’t given C a value to put in this variable yet. So what’s in there? What would we get if we asked for it? Well, let’s try it. Open Xcode and your Buzzword project and then open main.c. Now amend your program so it looks like the following (lines 17 and 18 are new):

You can see we are using printf in a slightly different way here.  Previously you’ve just used printf to display static information, but it has a few more tricks up its sleeve. The f in printf stands for “formatted”, because it also accepts things called conversion specifiers. These work in a similar way to the escape sequences you saw in the previous post. What a conversion specifier does is tells C, “I’d like to insert this type of information at this point please.” Conversion specifiers always start with %, which is followed by a single conversion character code representing the type of information we want to show. In this case we’ve use i (for integer – but note that you will also see %d used for an integer – either is fine, but be consistent). We also have to tell C what information to show at this point, so for each conversion specifier we include, we must also add a comma after the closing quote mark and a variable or some information of the correct type. In this example we want to show the score, so we’ve added our score variable.

If you run this you’ll see the instructions you added in the last post, and then something like this (don’t forget to use the Log Navigator if you want to see all of the output more clearly, but you can also scroll the Debug area at the bottom of the main pane):

xcode uninitialised c variable output

It will most likely be 0 but it could be a different number. The main thing to remember is that when you declare variables in this way, they contain garbage. You shouldn’t rely on them having any particular value until you set one. This is known as initialisation, and, once we’ve declared a variable, we can do it like this:

You can also declare a variable and initialise it in a single step, like this:

Let’s try this now. Change the current variable declaration in your programme so it looks like the line above and then try building and running again. You should see the instructions you added in the last post followed by:

Xcode c combined variable declarion and initialisation

So that’s great – we can store a number in a variable, and get it back again when we need it. But if this was a real score in a real game, we’d probably expect it to go up every now and then as the player accumulated points. C allows us to manipulate variables using operators. Operators perform common arithmetic operations such as adding, subtracting, multiplying and dividing. So, if our player had just won 10 points, we could add these to his score with a statement like this:

We can also use other variables in the equation. So if we had another variable called penalty, that contained the number of points to be subtracted if the player incurs a penalty, we remove those points with:

If we wanted to multiply the points by a bonus factor stored in the variable called bonus, we’d use:

Note that we use an asterisk, not an x for multiplication.

If we wanted to divide the points by the time taken, which we’d stored in a variable called time, we’d use:

Again, notice that we use a forward slash and not ÷ for division.

You can also combine operators in a single expression, e.g.:

If score was 1000 and bonus was 2 and time was 20, this expression would first calculate score * bonus, which equals 2000,  and then divide that by time, giving 100. However, consider this expression:

If score was 1000, penalty was 50 and bonus was 2, you might expect this expression would first calculate score – penalty, which equals 950, and then multiply that by bonus, giving 1900. But the number that would actually be put into score would be 900! Why is this?

Operators in C have what is known as an order of precedence. The order in which operators are applied within an expression depends on their order of precedence. You can find a table showing this order here: Operators in C and C++. You need to be looking at the table half way down the page in the Operator Precedence section, not the one at the top. Don’t worry that this is a big table with lots of operators you haven’t encountered yet – you’ll learn more about these in future posts. Where operators have the same precedence, e.g. * and /, they are applied in order of associativity, which you can see in the final column of the table. In the case of * and /, this is from left to right.

As you can see from the table, multiplication and division have a higher precedence than addition and subtraction, so what is actually happening in our expression above is that C is first calculating penalty * bonus, which is equal to 100 and then subtracting that from score, giving 900. To get the expression evaluated in the order you want, you can use parentheses, like this:

Parentheses will take precedence over multiplication and division operations. So, in this case, the part of the expression in parentheses will be evaluated first, giving us the correct result of 1900.

OK, that’s all good, but in our Buzzword programme we are much more concerned with letters than numbers. Well fortunately there’s a variable type that stores letters too. In your programme change the variable declaration/initialisation, and the printf line that follows it to:

Here we’ve changed to the type of our variable to char, which is short for character. Note that when we initialise char type variables, the initial value is placed with single quote marks. We’ve also changed the conversion character to c (for char).

When you build and run this, the end of the output should look like this:

xcode c char declaration and initialisation

OK great, but it’s going to be a bit long-winded if we have to do this for every letter of every word in our programme. Fortunately c has a way of dealing with collections of variables. Instead of declaring and initialising lots of individual variables, each with their own name, we can create a group of variables and give them a single name. This structure is known as an array.

For example, let’s say rather than recording just a single score, we wanted to keep track of the last five scores that a player had achieved. We could declare an array like this:

This looks similar to the way you declared a single int variable, but now you’ve added square brackets with a number at the end of the declaration. This tells C, “I don’t want a single variable, I want a group of five of them, and I want the group to be called scores”.

So, now that you have your array, how do you access the individual scores within it? The answer is that you use the square brackets again, like this:

This tells C, “please store the number 73 in the first variable of the group called scores”. Each variable within an array is called an element. Note that the first element of an array is numbered 0. That means the last element is always one less than the size of the array. In this case, to initialise the last element of scores you would use:

If you try to do this:

you will get an error, because that element doesn’t exist.

Here’s an example of how we could declare our array and initialise all the elements:

You’ll recall though, that there was a way we could declare and initialise single variables with a single statement. The same is also true of arrays. We do it like this:

This does exactly the same as the six statements in the previous example. Note that when we declare an array like this, we don’t have to include the number of elements between the square brackets because C can work this out based on the number of elements we’ve included in the initialisation list.

When we want to create a group of chars rather than ints we could do this:

We could now get the value of an individual element in this array, like this:

The number in square brackets that we use to reference a particular element is called a subscript. Remember that array elements are numbered from 0, so to get the nth element of the array, you would use the subscript n-1.

This is all well and good, but in C the reason we often want to group a set of characters together, is because we want to treat them as a single word or phrase. C provides us with a handy shortcut for doing this:

Note that this also results in an array of chars, but it is not quite the same as the char array we created earlier. This type of character array is called a string, because it is a string of characters. When you declare a char array like this, c adds an additional hidden element at the end. This is a special value called NULL, which you can also enter manually using the escape sequence \0. When c encounters this value it knows that it has reached the end of the string.

You’ve already been using strings, when you create a printf statement like:

The phrase between the quotes is known as a string literal because it is a string that is embedded within the programme code. We’ve used other literals when we’ve embedded other types of data directly in our programme. For example, the 73 in this statement is an integer literal:

Let’s see strings at work. Replace the current variable declaration/initialisation and the following printf statement with these statements:

Build and run and you should see the following at the end of the output:

c string example

This has introduced you to another conversion specifier, %s (for string). You can see from this example, that once you have declared and initialised a string, you can work with the whole string or with individual characters (elements of the array).

In the next part of this series you’ll see how you can use arrays to generate  the lists of words we need for Buzzword. In the meantime, here’s a challenge for you. Remove the two lines of code you just added and replace them with code that does the following:

1. Display the phrase: “10 green bottles hanging on the wall”. To make this a little bit more challenging, you must create the phrase so that the number at the beginning and the word ‘green’ are stored in variables.

2. When you have managed to get the phrase to display successfully, change it to “9 blue bottles hanging on the wall” by changing the values you use to initialise the two variables.

A solution will be shown in the next post.

 

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: your first programme

You can see an index of all the posts in this series: go to index.

If you are starting from this point, or need a fresh set of files, here are the starter files from the end of the previous post: first steps

In the first part of this series, you looked at Buzzword, the BASIC programme we’ll be converting and you also took your first steps with Xcode, the Integrated Development Environment (or IDE) we’ll be using to build it. Start up Xcode, if it’s not already running, and load the Buzzword project. If you’ve just reopened Xcode, you should see the project listed in the splash screen, so you can open it by double clicking on it from there:

Xcode recent files

If Xcode is already running but the project is not opened, select File, Open Recent, Buzzword.xcodeproj.

Make sure you can see the Project Navigator, and then open the main.c file.

I left you with a couple of exercises at the end of the last post. The first was to try and get the programme to display something other than the message “Hello, World!”, your name for example. If you completed this exercise successfully, you should have something that looks like this but with your name or personal message:

Buzzword exercise 1

When you build and run it, you should get something that looks like this:

Buzzword exercise 1 output

If you managed to get it to work, congratulations. As you have seen, printf will display whatever is between the quotation marks. But what about that strange character combination at the end? The second exercise was to work out what \n does. What did you come up with? If you tried putting it in the middle of the original phrase as I suggested, your code should have looked something like this:

Buzzword Exercise 2

And the output when you build and run should look something like this:

Buzzword Exercise 2 Output

You can see that everything after the \n appears on a new line. So that’s what these two characters do.

But why can’t you just hit the enter key in the middle of the message and insert a line break that way? Well let’s try it. Delete the \n and hit the enter key to insert a line break. Xcode will respond by showing error messages and if you try to build and run you’ll get a Build Failed! message.

Newline error

In C it is not permitted to put a physical line break into the middle of quotes like this. In fact there are a whole range of things you can’t insert, like tabs and backspaces for example. Because you might have a legitimate reason for wanting to include new lines or tabs or backspaces, C provides a way to include them by using what are known as escape sequences. These are the backslash character followed by a one letter code. You’ve already seen that \n is used for new line, others include \t for tab and \b for backspace.

You might be wondering what you do if you want to use the backslash character just as a straightforward backslash. Well there’s an escape code for that too – you use a backslash followed by another backslash: \\. A similar situation occurs when you want a double quote mark to appear in your message. If you just include it as it is, c will mistakenly think that’s the end of the message and you’ll get an error message again. You’ve probably figured out the solution. Yes, you use yet another escape sequence: \”. Here’s an example of how these are used with printf:

Of the six quotation marks used here, the four with a backslash in front of them will be displayed.

You might have noticed that this line of code ends with a semi-colon. A C programme is divided into a number of different statements. The semi-colon is how we tell C this is the end of the statement. You must remember to include a semi-colon at the end of every statement. If you don’t, C will complain by showing you error messages until you fix it.

OK it’s time to get started recreating Buzzword. If you refer back to the flowchart in the previous post, you’ll see that the first task is to show an introduction and some instructions. Let’s have a look at the start of the original BASIC programme to see how this is done:

Note that BASIC uses line numbers as a way of putting statements in order of execution. C doesn’t use line numbers – execution is determined by the order that statements occur in the file.

The command that BASIC uses to show information should look quite familiar, as it is very close to the C equivalent. Have a go at converting this to C and then building and running again. Don’t worry about the TAB instructions – we’ll show everything left aligned. By the way, when you see a PRINT statement without any quote marks following it, this is the BASIC equivalent of printf(“\n”);.

Here’s what my version looks like:

If  you chose to use several printf commands rather than just one, that’s fine too, but remember that C will run on the output from each of these. If you want a line break, you will need to explicitly put one in using \n.

Now when you try to run this, you’ll find that the output will run off the bottom of the tiny pane at the bottom of the screen. It’s time to introduce you to another Navigator. At the top of the Navigator pane, select the last icon, the one that looks like a speech bubble. This is the Log Navigator. It maintains a record of the output each time you run Buzzword. You can see the records of each time you have built and run in the Log Navigator. The latest run is at the top. Click this and you should now see the output from this run in the main pane. Your screen should look similar to this:

Xcode Log Navigator

So that’s the first stage of our Buzzword programme complete. In the next part of this series we’ll look at how we can store information in our programme.

Posted in Games, Programming Tutorials | Tagged , , , , , | Leave a comment

OS X games from the ground up: first steps

This is the first in a series of posts about designing and programming games for OS X.

You can see an index of all the posts in this series: go to index.

Part 1

Part 2

This series is called OS X games from the ground up because it assumes you are starting with a desire to create games but no prior knowledge of game design or programming. In this series I will introduce game programming concepts by converting a series of games from the book BASIC Computer Games by David Ahl. If you’d like to find out more about this book, and how to run the games in it – you can read this earlier post. Note though that compiling and running the simulator is an advanced topic and you don’t need it to be able to follow along with these posts. What you will need is a computer that is capable of running the latest versions of OS X (10.9.2 or later), such as a MacBook or iMac.

The first game we will convert is not really a game at all – it’s more of an amusement – but it does have the virtue of being simple. And simple is always a good place to start. The programme is called Buzzword. It generates amusingly pompous, but meaningless, jargon that you can introduce into the conversation around the board room table or dining table to show colleagues, friends and family how extraordinarily erudite you are (sorry – how much you know ;-)). If you want the original source code, you can get it here:BUZZWORD.BAS. Running the original BASIC programme generates something like this:

runBuzzword

Each time you run it, it randomly picks one word each from three lists of words – two lists of adjectives and one list of nouns and then shows the resulting phrase to the user. The user then gets the opportunity to decide whether to see another phrase or exit the programme. When approaching the design of any game, even one this simple, it always pays to map out the steps involved before you begin programming. A useful tool for doing this is a flowchart. In it’s simplest form this shows each step in a box connected with arrows to show the sequence. Decision points are shown with diamonds – you can see one in this simple flowchart for buzzword:

Buzzword flowchart

Having now planned what our programme needs to do, we’re ready to start the fun bit – programming. There are many ways to programme the Mac. For this exercise we are going to use a programming language called C. The C language has been around a lot longer than Macs – over forty years in fact. And while it’s not the easiest language to learn, it’s one of the most successful. And it’s still used today to create many games (and other applications), so getting a good understanding of C will stand you well in your games programming career.

Programmes in C are created initially as plain text files. So all you need to write one is a text editor of some sort. Apple’s TextEdit would do fine, but for this series we’ll use another Apple application that’s specifically for writing programmes. It’s called Xcode and you can download it for free from the App Store. When you’ve downloaded Xcode, start it up. You’ll see a splash screen that looks like this:

Xcode splash screen

Let’s get to work on our project straight away. Select Create a new Xcode project. If for some reason you don’t see the splash screen – or you’ve accidentally clicked past it- don’t panic. Just select the File menu then select New, then Project….

Xcode is designed for creating programmes for lots of different Apple devices – not just Macs and it has a selection of templates for different devices and project types. So first tell it you want to create a programme for the Mac by selecting Application under OS X on the left side of the window. Now you need to tell it what type of project you want to create, so select Command Line Tool from the right side of the window. Don’t worry about what this means for the moment – we’ll come back to this later. Your screen should now look like this:

Xcode select project template

Once it does, click Next. Now Xcode wants us to set some options for our new project. First we want to give it a Product Name. Enter Buzzword here. For Organization Name, use your name. The information in Company Identifier should uniquely identify you from every other developer. If you have your own domain name, put this in reverse, e.g. com.myuniquedomainname. If you don’t have a domain name, just use your full name again. This field is more important to get right if you are planning to distribute an app on the App Store, but for this exercise, anything will do.  The Bundle Identifier is created automatically based on your Company Identifier and Product Name. Again, this is important if you are planning to distribute your app commercially, but you don’t need to be concerned with it now. There are several languages you can use to programme the Mac. We’ve chosen c, but we need to let Xcode know that. Choose C from the Type drop down menu. Your screen should look similar to this, but with your own details in Organization Name and Company Name:

Xcode template options

Once you are happy with what’s on this screen, click Next. Finally Xcode will ask where you want to save the files it will create – choose a location – your documents folder for example. Make sure the Source Control checkbox is unchecked (we’ll explore this feature in a future post):

Xcode save project

When you have selected a location, click Create. Xcode will create a new folder at that location, using your Product Name as the folder name, and will then put some starter files in it. Your screen should now look like this:

Xcode initial project screen

At this point you are probably thinking “woah – that looks a lot more complicated than TextEdit!” Well yes, sorry – the learning curve is a little bit steeper – but I promise you that this investment will be rewarded. And don’t worry – we are going to tackle Xcode one bit at a time.

I mentioned that,when we created our project, Xcode very kindly created some starter files for us. So where are they? You should be able to see the main editor area in the centre of the screen. At present this probably has a lot of scary looking information on it – don’t worry about any of this for the moment. You might also see a narrower area to the left of the main area. This is the Navigator:

Xcode Navigator Pane

If you don’t see this area – don’t worry. It can be made to appear and disappear. Look at the toolbar on the top right and look for this icon:

Navigator icon

If it’s grey, not blue, click it and the Navigator will appear. If the Navigator appears but shows different information to what’s shown in the screenshot above, then find this set of icons towards the top of that pane and select the first one that looks like a folder:

Xcode Navigator icons

Each of those icons is a different type of Navigator. They allow you to navigate through different aspects of the project. The one you use will depend on what task you are working on at any time. At the moment you are looking at the Project Navigator. This shows the files in the project and this is where you’ll spend most of your time while you are writing code. You should be able to see a couple of files here that Xcode has created for you. As you create new files, they will also appear here.

Files here can be arranged into Groups. Groups have a folder icon. This doesn’t necessarily mean those files are in a folder of that name on your hard drive, it’s just a convenient way of grouping them in Xcode. You can show or hide the files within a group by clicking the disclosure triangle next to the group name. Try this now by clicking the disclosure triangle next to the Buzzword group a couple of times. Leave it open when you’re done. In time I will explain what all these files do, but for now the one you are interested in is called main.c. Click this once and it should be displayed in the large central pane, which should like like this, but with your details shown in the copyright notice:

Xcode initial c app

So what is all this stuff that Xcode has already given you? This is actually a fully functional c programme. It’s something of a tradition when learning programming, that your first ever programme displays the message “Hello, World!”.  This tradition was started by Brian Kernighan, who was one of the authors of the first book to describe the C language you’re about to learn.

So I’m sure, having done all that hard work to get to this point, you’d like to see this programme running. Although the programme is written in plain text, and makes a lot of sense to humans (at least it will do, once you have learned a bit more), it’s not so useful for machines in this format. Although there are many different languages that can be used to programme your Mac, it really only understands one. This is called machine code, and it’s a series of numbers that represent the instructions the Mac’s CPU is able to carry out. Programming directly in machine code, which is known as a low-level language, can be done, but it is a very difficult and time consuming process. Instead we use a high-level language, like C, which is easier for us to understand, and then convert this to the equivalent machine code that the Mac can run. With C, we do this using a process called compilation. This process involves another programme, called a compiler, reading all the files and then translating them into the equivalent machine code.

One of the reasons we opted to use Xcode is that, not only does it act as an editor that you can create your programme files, it also runs the compiler for you, along with a host of other useful things you’ll find out about later. Xcode is actually an example of a type of application called an Integrated Development Environment (or IDE). The integrated bit is because they combine all the activities you are likely to want to complete as a developer within one package. Shakespeare might have had Julius Caesar being told to beware the ides of March, but there’s absolutely no need to beware the IDE of Apple – in fact it will make your life a whole lot easier, once you’ve grown comfortable with it. Let’s see an example of that now. To compile and run our programme, simply click the dark grey play button near the top left of the window:

Xcode run button

 

All being well, a new pane should appear at the bottom of the main window showing the message “Hello, World”:

Xcode debug pane

In the next part of this series we’ll start modifying this template to create the Buzzword programme. In the meantime, here’s a couple of exercises for you.

1. Try and change the programme so it displays something other than “Hello, World!”, e.g. your name. Once you have made your change, click the build and run button again (the one that looks like a play button) to see the result. If you see a message that says “Build Failed” instead, this means you have done something to break the programme. Don’t worry – just put everything back as it was (refer back to the screen shot of the original code if you need to) and then try again.

2. Can you work out what the characters \n do at the end of the message? Here’s a hint – try moving them to the beginning of the message (just after the opening quotation mark) or to the middle of the message (e.g. just after the comma) and then build and run and see what happens.

I’ll show you solutions in the next post.

Posted in Games, Programming Tutorials | Tagged , , , , , | 1 Comment

Running old BASIC computer games

If you’re a computing enthusiast who’s been around for a while, you may remember David Ahl’s classic books, BASIC Computer Games and More BASIC Computer Games, from 1978 and 1979 respectively. These two volumes contained BASIC listings for many games taken from the pages of the hobbyist magazine Creative Computing.

ahlBooks

These books provided a popular source of games to build and experiment with for people who acquired microcomputers in the late 1970s and early 1980s. All of the games in the book are designed to run in Microsoft BASIC on systems with a simple teletype terminal. Partly as an exercise in nostalgia and partly as an exercise in programming, I decided to make updated graphical versions of some of the games from these books.

Many of the games are very simple and you can easily understand the algorithms from just examining the listing and looking at the example printouts of the game running. Some are more complex – and for these it is useful to be able to see the game running. So I had my first challenge: how could I run games written in a language that is almost 40 years old and intended to be used on systems that you’d be lucky to find outside of a museum or an e-bay auction?

Ideally I wanted to be able to run the games on my MacBook in OSX Mavericks. Looking at the introduction to the books reveals that most of the games were written in Microsoft 8080 BASIC on an Altair 8800 with 16K of RAM. Obtaining, restoring and running an original hardware 8800 is not impossible, but potentially difficult and expensive. Fortunately, there’s another option. As the MITS Altair 8800 was a popular machine there are a few emulators out there for modern platforms.

A good option for OSX seemed to be a popular multi-system simulator called SIMH. This has two Altair 8800 simulators that simulate the systems based on both the 8080 and the Z80 chipsets. Some research turned up a few binaries for OSX, but all of those that I found seemed to have been compiled for PowerPC Macs and were unceremoniously spat out by my Intel-based MacBook.

Fortunately SIMH is very actively maintained by a group of enthusiasts and the current codebase can be found on GitHub. I cloned it from https://github.com/simh/simh.git using the GitHub app.

Building SIMH was a breeze thanks to the comprehensive and well-maintained makefile. After starting Terminal and navigating to the folder containing the source files, entering make all will build all the currently supported simulators. I received a warning during the build, but this was because of a formatting issue and the binaries were created successfully.

The makefile creates a BIN folder with all of the simulators as Unix executables. There are two Altair simulators. I chose to use Altairz80. The simulator is run by navigating to the relevant folder in Terminal and then entering either altairz80, if the folder is included in the PATH environment variable, or ./altairz80 if it isn’t. If the simulator has compiled successfully, it responds with the following:

runAltair

So far so good, I had the start of a working environment. The next challenge was to get those BASIC games up and running. The website of Peter Schorn, the creator of the AltairZ80 simulator, has a collection of operating systems for the Altair. These include a CP/M 2.2 bundle that includes Microsoft BASIC and Eliza, one of the games from the books. After downloading, these files should be placed in the same folder as the simulator. CP/M can be started within the simulator by entering do cpm2.

The terminal should now be showing:

runCPM

Microsoft Basic can be started by entering MBASIC:

runMBASIC

A game can then be loaded with, for example, LOAD “ELIZA.BAS” and then run with RUN:

runEliza

So now I had a fully working environment, it was time to get the games. The full text of both books is available at atariarchives.org:

BASIC Computer Games
More BASIC Computer Games

One option at this point is to simply type in the games by hand – remember doing that? – and then save them to the virtual disk with e.g. SAVE “CHECKERS.BAS”. Fortunately a lot of them have been collected here: http://www.classicbasicgames.org, which saves some considerable hours of monotonous typing.

To get the listings from this site into the virtual disk I first saved them as text files on my MacBook, using a CP/M compliant filename, i.e. maximum of 8 characters followed by a dot and a three character extension e.g. ACEYDUCY.BAS. The files must be saved to the folder containing the simulator and the CP/M image.

Now to get them into the virtual disk image, you start the simulator and CP/M and then use the R (read) command, e.g. R ACEYDUCY.BAS:

readCommand

If you now get a directory listing, using DIR, you should see the file has been added to the virtual disk image:

directoryListing

Now you can start MBASIC and load and run the game as normal:

runGame

Posted in BASIC, Games, Retro Computing | Tagged , , , , , , , | 1 Comment