Sunday, June 5, 2011

Code a Guessing Game

Now we have our first game. What game? You probably played it before. It's called, "I'm thinking of a number between one and ten." Now normally, you have a bunch of your friends attempting to guess correctly and whoever wins gets to wash the dog first. In this case, you will have to do all the guessing yourself. Let's start with this version of the game:
Now there are several things to notice in this. First of all we have a new command. This one is called while. It will do whatever is indented under it over and over until the comparison of guess and secret turn false. How does it turn false? You guess the correct number. So we need to tell the computer to have the comparison work as long as the guess is not equal to our secret number. For some reason, programmers decided that an exclamation point (!) should be called "not", so we create not equal with !=.

Another thing about this game. It's boring. Why? Because we know the secret number. It's five. It's written right at the top of the program. But there is a way to be able to change things, but we have to get it from outside of the built in functions in our programming language:
Okay, that's better. Now I have no idea what secret is. In fact, it will change every time I click the Run button. But we had to do some interesting things to get there. First we had to import some code that makes the computer be able to pick a random number. Then we had to use that code by typing a period (.) after random so you could use one of its functions. All random's functions are inside random, and you use a period to get to them. The function we are using is called randint and we give it two numbers to tell it how low and high it can go when picking a number.

One thing. Why is it called int? It's short for integer, which means all whole numbers, positive or negative.

Now let's give the guesser a hint so we know if they need to guess higher or lower:
So now we know the answer to what to do if you need something inside a while and inside an if. You indent twice. Also, we have a new comparison. It's a less-than (<) comparison. If you're daring, change the secret random number to between 1 and 100, and see how quickly you can guess it.

No comments:

Post a Comment