BWD Chapter 06: What number am I thinking of?

2004-11-01 22:19 - Beginners Web Development

Chapter 06
What number am I thinking of?

To whet your appetite, I will start off this chapter by saying that by the end we will have written our first computer game. Now, we just have to figure out how!

One of the simplest parts of a game is that the player must be able to play. Otherwise it is not a very fun game! We will let the player play this game by typing a value in with his keyboard. We will need to keep track of what he types (in a variable) and then check to see if he won the game.

It will be a simple guessing game. The player will enter a guess from 1-10 and the computer will say if they guessed the right number. Can you imagine how the program might look? How about the pseudocode for the program? It will be a bit like this.

pick a secret number
ask the player for a number from 1 - 10
if the players number = the secret number
  congratulate the player for winning
if not
  tell the player he lost

Pretty easy right? Yeah, except for one tidbit we haven't covered yet. How do we ask the player for a number? Don't worry it isn't hard at all. We use the INPUT statement. The basic format for the INPUT statement as we need to use it looks like this;

INPUT prompt, variable

Where prompt is a string which will be shown to the user, and variable is where his answer will be stored. You will usually want to put a space at the end of the prompt string, to separate it from what the user types.

So now we get to write our game. You may want to experiment with the INPUT statement first, but your challenge now is to turn the pseudocode above into a real program that actually plays this game. The answer is below but don't peek! Your answer probably will not match mine exactly, even if it is right. Do not worry, there are many right answers.

secret = 7 INPUT "I have a secret number from 1 - 10. Can you guess it? ", guess IF (secret = guess) THEN PRINT "Yes my number was seven, you win!" ELSE PRINT "No that is not my number, try again!" END IF

In this program we used variables, assignment and comparison operators, user input, conditional and print statements. Getting complex quickly, no? If you had trouble you may want to reread the past few chapters or spend a little extra time pondering the concepts behind each topic I just listed.

Comments:

No comments!

Post a comment:

Username
Password
  If you do not have an account to log in to yet, register your own account. You will not enter any personal info and need not supply an email address.
Subject:
Comment:

You may use Markdown syntax in the comment, but no HTML. Hints:

If you are attempting to contact me, ask me a question, etc, please send me a message through the contact form rather than posting a comment here. Thank you. (If you post a comment anyway when it should be a message to me, I'll probably just delete your comment. I don't like clutter.)