The First Game: KONG

[ LiB ]

Alright, now you will be able to see what a full game looks like. This is basically a simple Pong clone, and it is easy to control and play. The idea of this game is to score more points than your opponent by hitting the ball past his side of the table. To play, either run demo01-01.exe from the CD or compile the code.

To compile the code yourself, you need to find demo01-01.bb on the CD. After finding it, copy it to your computer and open it through the Blitz Basic compiler. To open it, find the File menu on the top of the compiler and click Open . Navigate to demo01-01.bb and press Enter. The code should now appear inside your compiler.

To actually compile, find the Program toolbar in Blitz Basic. Select Program->Run Program, and the game will compile and run! You have just compiled your first program!

Feel free to examine the code; although it may seem very weird and hard to understand now, you will soon be able to figure out this code easily.

Table 1.3 lists the keys you will use for this game.

Table 1.3. Keys Used in KONG

Key

Action

Up Arrow

Move player up

Down Arrow

Move player down

Escape

Exit game

P

Pause and Unpause


Okay, let's actually take a look at the code. Read it, but don't worry if some of it is hard to understand. This is the first program you have seen, and it isn't easy. You will learn how to actually write this code throughout the book.

 ;demo01-01.bb - A Complete game of KONG ;Set up graphics mode Graphics 800,600 ;Seed the random generator (make random numbers actually random) SeedRnd(MilliSecs()) ;Create a back buffer SetBuffer BackBuffer() ;Set the handle to the center of images AutoMidHandle True   ;CONSTS ;The following are key code constants Const UPKEY = 200   ;Up Const DOWNKEY = 208  ;Down Const PAUSEKEY = 25  ;P  Const HUMANSPEED = 7 ;The human's max speed Const COMPUTERSPEED = 6 ;The computer's max speed   ;TYPES ;The player type: both the human and the opponent Type player       Field y,score;y position and score End Type ;The ball type: for the ball Type ball       Field x,y,xv,yv     ;x, y coordinates, and x, y velocity End Type ;IMAGES ;The picture of the human player Global player1image = LoadImage("player1.bmp") ;The picture of the computer player Global player2image = LoadImage("player2.bmp") ;The picture of the ball Global ballimage = LoadImage("ball.bmp") ;Load the ball image ;TYPE INITIALIZATION ;Create a ball Global ball.ball = New ball ;Create the human Global player1.player = New player ;Create the computer Global player2.player = New player 

This is the end of the declaration section of the code. This part sets up the important variable for the program, as well as the types and images. (Don't worry; you will be introduced to all of this as the book progresses.)

After the declaration, we begin the initialization. Initialization is the process of setting up everything that will be used in the programin this section, the initialization section sets up the beginning score values and the players' position on the screen.

 ;INITIALIZATION Text 400,300,"Ready...Set" ;Wait for one second Delay(1000)  Text 420,330,"GO!!!" Flip ;Delay for 1/5 of a second Delay(200) ;Initialize the level InitializeLevel()   ;Set inital scores player1\score = 0 player2\score = 0 

The initialization section sets up some important variables for the game, such as the score and the player variables. These variables keep track of how the player is doing and where he is located.

After initialization, the actual loop begins:

 ;MAIN LOOP While Not KeyDown(1) ;Clear the screen Cls ;Draw the ball DrawImage (ballimage,ball\x,ball\y) ;Draw the human DrawImage (player1image, 60, player1\y) ;Draw the computer DrawImage (player2image, 740, player2\y) ;Test what user pressed TestKeyboard() ;What should AI do? TestAI() ;Draw the HUD DrawScore() Flip Wend ;END OF MAIN LOOP 

NOTE

What Is a Frame?

I am about to reference the word "frame" a bunch of times in a few moments, and you should know what it means. A frame is the screen at any given moment. A game can be compared to an animated film both are made up of a bunch of different pictures that, when put together, create animation. The frames blend together so quickly that the objects on the screen appear to be moving. An average game runs at 30 frames per second, which means 30 pictures on the screen are blended together each and every second.

This is the end of the main loop. To put it bluntly, the main loop is the entire game. Every frame of a game is one iteration of the main loop. By the way, a loop causes some code to be repeated over and over until some condition becomes false. Here, the condition is that the Esc key has not been pressed. Usually, the main loop is a while loop, shown here in the line

 While Not KeyDown(ESCKEY) 

At this point, the actual game loop has been completed, so we must now define the functions. A function is called with its name followed by parentheses; for example, InitializeLevel() . Functions are like little helpers that perform specific activities that we want to do over and over. If you look at the main loop, you will see that most of these functions are called from there, and some others are called from within other functions.

 ;INITIALIZELEVEL() ;Sets up starting values Function InitializeLevel() ;Put ball in center of the screen ball\x = 400 ball\y = 300 ;Make the ball move in a random direction ball\xv = Rand(2,6) ball\yv = Rand(-8,8) ;Place the players in their correct position player2\y = 300 player1\y = 300 End Function 

This function sets up the starting values for the players and the ball. The ball is in the center of the screen, and it is directed toward the right of the screen (to the computer player's side) with a small variation on how high or low it goes. The human player is near the left edge of the screen, and the computer player is near the right.

 ;DRAWSCORE() ;Draws the HUD in the top right Function DrawScore() ;Write the human score Text 700,0,"Player 1: " + player1\score ;Write the computer's score Text 700,30,"Player 2: " + player2\score End Function 

This is probably the simplest function in this program because all it does is draw the scores on the top-right corner of the screen.

 ;TESTKEYBOARD() ;Moves player up and down based on keyboard Function TestKeyboard() ;If player hits up, move him up If KeyDown(UPKEY)     player1\y = player1\y - HUMANSPEED EndIf ;If player presses down, move him down If KeyDown(DOWNKEY)     player1\y = player1\y + HUMANSPEED End If ;if player presses Pause, pause the game If KeyHit(PAUSEKEY)     ;make screen blank     Cls     Text 400,300,"Press 'P' to Unpause Game"     Flip     ;wait for player to unpause     While Not KeyHit(PAUSEKEY)     Wend EndIf End Function 

This function determines what keys the user pressed, if any. If it doesn't make sense to you, try reading the following pseudocode:

NOTE

What Is Pseudocode?

Big word, huh? Pseudocode is a very helpful device in game programming because it takes hard-to-understand concepts and turns them into human language. Pseudocode is the program code put into easier-to-understand terms. Basically, to convert code into pseudocode, simply change each line of code into human language. However, pseudocode does not have all the detail that real code does, so although it is good for understanding concepts, it isn't a good idea to try and put it back into a program.

 If (  player presses up  )  Move player up  If (  player presses down  )  Move player down  If (  player presses 'P'  )  Pause the game  

Pretty easy to understand, don't you think? Refer back to the actual code to see the correlation.

Next we look at the function TestAI() .

 ;TESTAI() ;Updates ball and score and enemy Function TestAI()  ;If ball is above computer, move computer up If ball\y > player2\y     player2\y = player2\y + COMPUTERSPEED   ;if ball is lower than computer, move computer down ElseIf ball\y < player2\y      player2\y = player2\y - COMPUTERSPEED     EndIf ;If ball hits human player, reflect it away from him and variate its velocity and direction If ImagesOverlap(ballimage,ball\x,ball\y,player1image,60,player1\y)     ball\xv = -ball\xv + Rand(-4,4)     ball\yv = ball\yv + Rand(-4,4) ;If ball hits computer, reflect it away from computer and variate its velocity and direction ElseIf ImagesOverlap(ballimage,ball\x,ball\y,player2image,740,player2\y)     ball\xv = -ball\xv + Rand(-4,4)     ball\yv = ball\yv + Rand(-4,4) ;If ball hits top wall, reflect it downwards ElseIf ball\y <= 0     ball\yv = -ball\yv + Rand (-1,1)     ball\xv = ball\xv + Rand (-1,1) ;If ball hits bottom wall, reflect it upwards ElseIf ball\y >= 600     ball\yv = -ball\yv + Rand (-1,1)     ball\xv = ball\xv + Rand (-1,1) ;if ball hits left wall, computer has scored so computer gets one more point ElseIf ball\x <= 0     player2\score = player2\score + 1   ;computer scores     Text 400,300,"Player 2 Scores!!!"     Flip     ;wait two seconds     Delay(2000)     ;reset level     InitializeLevel() ;If ball hits right wall, human scored so give him a point ElseIf ball\x >= 800     player1\score = player1\score + 1   ;human scores     Text 400,300,"Player 1 Scores!!!"     Flip     ;wait 2 secs     Delay(2000)     ;reset level     InitializeLevel() EndIf        ;update ball's position on screen     ball\x = ball\x + ball\xv     ball\y = ball\y + ball\yv End Function 

This one is a lot harder to understand. TestAI() changes the position of the ball based on its direction variables, and changes the position of the computer's paddle based on the position of the ball. It also increments the score if either team hits the ball past the opposing paddle. If you are having trouble understanding this function, maybe the following pseudocode will clear it up:

 If (  ball is above computer  )  Move computer up  OR if (  ball is below computer  )  Move computer down  If (  ball hits player's paddle  )  Change direction of ball  OR if (  ball hits computer's paddle  )  Change direction of ball  OR if (  ball hits top wall  )  Change direction of ball  OR if (  ball hits bottom wall  )  Change direction of ball  OR if (  ball hits left wall  )  Score a point for computer   Reset the level  OR if (  ball hits right wall  )  Score a point for the player   Reset the level  

NOTE

CAUTION

Because of margin constraints, some of the lines of code may have spread over two lines or more. In a real game, all of the code must be on one line, or else it won't run. For example, if I had written something like the following line:

 ElseIf ImagesOverlap(ballimage,ball\x,ball\y, player2image,740,player2\y)  ;This tests to see if the ball has collided with player 2's image. 

Typing it into the compiler with the line break would not work. It must be on the same line, even though the margins in the book make it appear broken up.

Once again, if you want to have a better perspective of this game, run demo01-01.bb off the CD.

Figures 1.7 and 1.8 show the KONG title screen and main screen, respectively.

Figure 1.7. KONG title screen.


Figure 1.8. KONG main screen.


Compiling the Code

Compiling the code is a very simple procedure. Just open the file (demo01-01.bb) off the CD in Blitz Basic (or type it into the workspace), save the file (File->Save) onto your computer, and select Program->Run Program, as shown in Figure 1.9.

Figure 1.9. Compiling the game.


Well, that isn't what you would call a full game. I did not add any special effects or sounds because they aren't very important at this point. The idea is to get a feel for what code looks like and how it is written. You will notice that the meanings of most of the functions are easy to understand because of the function names . This helps in understanding the program.

Let me summarize the points that I've touched on so far. Many games consist of three main parts :

  • The initialization section

  • The main loop

  • The shutdown

Initialization sets up variables and functions that are used throughout the game. Declaration is part of initialization and is used to set up variables that will be used later in the program. The game loop is what you see on the screen. Each iteration (an iteration is each time the program runs through the loop) of the loop is one frame of the game. Usually, there are at least 30 frames, or iterations, per second. See Figure 1.10 for a description of initialization, the game loop (also known as the main loop), and shutdown in KONG.

Figure 1.10. Initialization, game loop, and shutdown.


The shutdown sequence is the final part of the game, and it runs just before and during the end of the game. It closes all open files, deletes any running variables, and quits out of the game.

Of course, there are a few other important parts to any game, but I will go over them with you when learning about them is necessary. For now, read over the commented code (on the CD) and try to understand what the heck is going on. If you follow the functions, it shouldn't be too hard.

[ LiB ]


Game Programming for Teens
Game Programming for Teens
ISBN: 1598635182
EAN: 2147483647
Year: 2004
Pages: 94
Authors: Maneesh Sethi

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net