Games programming is a very challenging area of programming. As well as design skills and a knowledge of games, it requires a high level of programming ability.
As an introduction to games programming we will build a simple guessing game. This is the first step on the ladder to building your dream all action driving/platform/shoot-em-up/rpg.
In order to complete this tutorial you should already have some familiarity with using Flash and have completed the 'Input Text' tutorials.
In this tutorial you will create a simple guessing game. The program will simulate a dice roll by picking a random number between 1 and 6, and you have to guess that number to win. You will be given one opportunity to get the number right.
First we will look at generating random numbers and make a program that picks a random number between 1 and 6 and displays that number on the screen. See example below:
on (release){
myRandom=Math.floor(Math.random()*6)+1;
randomNum.text=myRandom;
}
Explanation of the code: the function Math.random() picks a random number between 0 and 0.999. If we multiply that by 6 we get a random number between 0 and 5.999. If we add 1 to that we get a random number between 1 and 6.999. The problem is that it doesn't do whole numbers - it picks ANY number , for example, 4.1, 1.09, 2.45. etc. To deal with this we use the Math.floor() function to round the number down.
on (release){
if (randomNum.text==guessNum.text){
messageText.text="Well Done!";
} else {
messageText.text="Wrong!";
}
}
This code checks the user input against the randomly generated number and displays the appropriate message depending on whether the user guesses correctly or not.
Try the game below - press 'Generate' to pick a random number, then type a guess and press 'Check Guess' to see if you guessed correctly. Of course, to make the game more of a challenge you need to remove the text box that displays the randomly generated number! - but having the number shown lets you test the program is working correctly.