ITP 134 Study Guide – Chapter 7 The Game Loop and Animation

ITP 134 C++ Programming Notes

Instructions: Use these notes to give you the important points of this chapter. See the book for lots of great programming examples. Important concepts, keywords, statements and functions are shown in emphasized font.Programming code syntax and examples are shown in code font. Updated 4/4/2011.

ITP 134 – Chapter 7Mrs. EatonPage 1

ITP 134 Study Guide – Chapter 7 The Game Loop and Animation

Chapter 7 The Game Loop and Animation

ITP 134 – Chapter 7Mrs. EatonPage 1

ITP 134 Study Guide – Chapter 7 The Game Loop and Animation

7.1 The Game Loop

CONCEPT:The game loop is a special loop used in games and animation programs. It synchronizes the refreshing of the screen with the program’s other operations. (pg 281)

  • You learned about loops as one of the 3 basic control structures in Chapter 6. You will learn about animation loops and working with refreshing the screen with animations in this chapter.

Functions that synchronize the animations and calculations with refresh screen rate. (pg 283-285)

  • dbSyncOn – This function tells the DarkGDK that we want our program to handle the updating of the screen. As a result, the Dark GDK will NOT attempt to update the screen until we tell it to.
  • dbSync – This function forces a screen update.
  • dbSyncOff - This function gives the control back to the computer for automatic refreshing of the screen.
  • dbSyncRate – This function accepts an argument that specifies the maximum times per second that the screen should be updated. This value is commonly referred to as the frame rate or the refresh rate. The rate range is 0 - 1000. Using 0 refreshes the screen as fast as possible.
  • LoopGDK – This function is used to control the number of times that a loop executes per second. It also tell us, via its return value, whether the user has attempted to end the program.

The LoopGDK function returns:

0 if the user has closed the program, or pressed the Esc key.

Otherwise it returns a nonzero value (useful for using as a Boolean to repeat or not.)

The Game Loop

This is the normal process to create a game loop to refresh the screen. See Figure 7-1 Game Loop Code for details (pg 285).

//disable auto refresh

dbSyncOn();
// set refresh rate 0 is fastest

dbSyncRate(MaxRefreshRate);

// loop until user closes program

while ( LoopGDK() )

{

// draw graphics etc.

Statements;

// force screen refresh

dbSync();

} }

Giving Control Back to the Dark GDK

Use dbSyncOff from the GDK Library to give control back for automatic screen refreshing. To display prompts, call dbSyncOff just before you display the user prompt, and then call dbSyncOn after user enters the value. (pg 285)

7.2 Simple Animation

CONCEPT: A simple way to create an animation is to write a game loop that draws a shape at a different location during each iteration. Be sure to clear the screen between iterations. (pg 286).

Clearing the Screen in the Game Loop

See Figure 7-3 Drawing the ball without clearing the screen for an example of what happens if you forget to clear the screen between iterations. (pg 289)

7.3 Controlling Objects with the Keyboard

CONCEPT: The Dark GDK provides functions that let you know whether certain keys, such as the arrow keys, spacebar, Enter key, and so forth are being pressed. Many games and animation programs allow the user to control objects on the screen with such keys. (page 289)

Key Detection Functions

  • See Table 7-2 Key Detection functions for more details (pg 290).
  • The following functions return true (1) if the corresponding key is being pressed by the user. Otherwise the function returns false (0): (pg 290)
    dbUpKey – Up arrow key
    dbDownKey – Down arrow key
    dbLeftKey – Left arrow key
    dbRightKey – Right arrow key
    dbControlKey – Ctrl key
    dbShiftKey - Shift key
    dbReturnKey – Return key
    dbEscapeKey – Esc key
    dbSpaceKey – spacebar

Letting the User Move an Object

  • Most games allow the user to move an object (such as a character) around the screen during game play. You can program the keyboard keys so you can move a character.

Performing Other Operations with the Keyboard

  • You can use other keys beyond the arrow keys to do more operations in addition to moving objects. For example, you could use the spacebar to shoot objects.

7.4 Sprites

CONCEPT: A sprite is a graphic image that is used as an element in a game. Sprites can be moved and manipulated in various ways. Note by Eaton: See Wikipedia for historic definition of sprite. (pg 296)

Creating a Sprite

To create a sprite requires 2 steps. (pg 296)

  • Use dbLoadImage function to load an image into memory to use as a sprite
  • Use the dbSprite function to designate the image as a sprite.

ITP 134 – Chapter 7Mrs. EatonPage 1

ITP 134 Study Guide – Chapter 7 The Game Loop and Animation

Sprite Functions

This table shows the functions that are used for sprite and animations described in Section 7.4

Page / Function / Description
296 / dbSprite(#, x, y, ImageNumber) / Create a sprite using an image that has already been loaded using dbLoadImage function.
298
309 / dbSprite(#, x, y, ImageNumber) / Move an image to a new location by changing the x,y coordinate position or assign a different image to the same sprite.
301 / X = dbSpriteX(#) / Get the x coordinate position of sprite #
301 / Y = dbSpriteY(#) / Get the y coordinate position of sprite #
302 / width = dbSpriteWidth(#) / Get the width of existing sprite #
302 / height = dbSpriteHeight(#) / Get the height of existing sprite #
302 / dbRotateSprite(#, angle) / Rotate sprite # 0-360 degrees around the sprite's insertion point
304 / dbOffsetSprite(#, XOffset, YOffset) / Change sprite's insertion point . The default is the upper left corner.
307 / dbHideSprite(#) / Make a sprite invisible.
307 / dBShowSprite(#) / Make a sprite visible that was previously hidden.
307 / dbHideAllSprites() / Make all sprites invisible.
307 / dbShowAllSprites() / Make all sprite visible that are hidden.
307 / dbSpriteVisible(#) / Determine if a sprite is visible or hidden. Function returns 1 (true) if sprite is visible, otherwise it returns 0 (false).
307 / dbSizeSprite(#, width, height) / Resize sprite # by specifying width and height.
Page / Function / Description
308 / dbStretchSprite(#, width%, height%) / Stretch or shrink sprite # a percentage. Value of 50 would shrink to 50% of size.
308 / dbSetSpritePriority(#, priority) / Change sprite # priority. Default priority is 0. Larger values have higher priorities and will be drawn on top of other sprites.
309 / dbSpriteExist(#) / Determine whether a sprite was created successfully. Returns 1 (true) if exists and 0 (false) otherwise.
310 / dbFlipSprite(#) / Flip a sprite vertically.
310 / dbMirrorSprite(#) / Flip a sprite horizontally.
311 / dbSetSprite(#, backsave, transparency) / By default, a sprite is set to restore its background as it move and use transparency. For backsave, 1 will enable and 0 will disable. For transparency, 1 will enable and 0 will disable.
311 / dbSetSpriteAlpha(#, alpha) / This is different from color key. Alpha values from 0-255 where 0 is invisible and 255 is totally opaque.
312 / dbDeleteSprite(#) / Remove sprite from memory.
317 / dbPasteSprite(#, x, y) / Make a copy of a sprite. When you paste a sprite the copy is dependent on the original sprite.
318 / dbCloneSprite(#, clone#) / Make a copy of a sprite. When you clone a sprite the clone is independent of the original sprite.
327 / dbCreateAnimatedSprite(#,
filename, Columns, Rows, Image#) / Create an animated sprite from a sprite sheet (filename).
327 / dbPlaySprite(#, start, end, delay) / Extracts images from a sprite sheet starting from the start frame, ending with end frame with a delay in milliseconds. Use dbSprite function to display sprites.
330 / dbSpriteCollision (sprite#1, sprite#2) / Determine whether 2 sprites have collided. Returns 1 (true) if have collided, and 0 otherwise. Uses the bounding rectangles of each sprite to determine collisions.

ITP 134 – Chapter 7Mrs. EatonPage 1

ITP 134 Study Guide – Chapter 7 The Game Loop and Animation

dbSprite function (general use pg 296)

For example (pg 296):

dbLoadImage(“LadyBug.bmp”, 1);

dbSprite(1, 320, 240, 1);
// Create sprite#1 at position (320,240) using image #1

Displaying Sprites, Images and Primitive Graphics

When you create a sprite in a Dark GDK program, the program goes into a special mode that allows sprites to move around on the screen and pass in front and behind each other without interfering with each sprite image.

The process is known as back saving where a sprite B image is restored if sprite A image moves from the same location. Sometimes you need to create programs that display sprites along with regular images

and primitive graphics. Your program will perform faster if you only create sprites for the elements that move in your game, however, this can cause problems with back saving and leave trails of images, or erases everything except sprites from the screen. (pg 313)

Pasting and Cloning Sprites

There are two ways to make a copy of a sprite: pasting and cloning (pg 317)

  1. When you paste a sprite, you make a copy that is dependent on the original sprite. When you change the original sprite, the same operation will automatically be applied to any pasted copy as well.
  2. When you clone a sprite, you are making a copy that is independent of the original sprite. If you change the original sprite, it has no effect on the cloned copies.

7.5 Cel Animation and Sprite Sheets

CONCEPT: You can create a simple animation by displaying a sequence of images one after the other.

This can be done by manually loading and displaying separate images, or via an animated sprite sheet. (pg 323)

See Figure 7-17 Cel animation images for an example of 8 separate walking man images. (pg 323)

Simplifying Animation with Sprite Sheets

The Dark GDK supports sprite sheets that contain several frames on an animation sequence in a single image file. (pg 325)

See Figure 7-18 A sprite sheet for an example of a sprite sheet that contains 8 frames on the walking man animation. (pg 326)

See Figure 7-19 A sprite sheet with 2 rows and 4 columns for an example of a sprite sheet that contains 8 frames in 2 rows and 4 columns of a clock animation. (pg 326)

Playing Sprite Animations with the Dark GDK

An animated sprite is a single sprite that is used to display the images in a sprite sheet, one by one. To create an animated sprite, use the dbCreateAnimatedSprite function.

For example (pg 327),

dbSpriteAnimatedSprite(1, “animation.bmp”, 3, 2, 10);

// creates sprite #1 as an animated sprite and loads “animation.bmp” as image #10

Once you have created an animated sprite, you use the dbPlaySprite function to extract the frames from the sprite sheet. This function does not display the image. To display the image use the dbSprite function. The general syntax is (pg 327):

dbPlaySprite(SpriteNumber, StartFrame, EndFrame, Delay);

7.6 Sprite Collision Detection

CONCEPT: A collision between sprites occurs when one sprite’s bounding rectangle comes in contact with another sprite’s bounding rectangle. Collisions between sprites can be detected. (pg 329)

A sprite’s bounding rectangle will be the size of the sprite’s image file.
Eaton note: Your sprite image should be trimmed to the minimum size needed to display the entire sprite. (pg 329)

Use the dbSpriteCollision to determine if two sprites have collided. If the sprites have collided the function returns true (1), otherwise it returns false (0). A collision occurs if the bounding rectangles of the 2 sprites overlap. The general syntax is (pg 330):

dbSpriteCollision(SpriteNumber1, SpriteNumber2);

Chapter 7 Programs

Program 7-1 InfiniteLoop.cpp (pg 282)

This program is an example where you will not see any output because the screen refresh rate cannot keep up with the calculations. This program uses an infinite loop which you should never use.

Program 7-2 InfiniteDots.cpp (pg 283)

This program updates the previous program so that it actually displays dots on the screen using the new dbSyncOn, dbSyncRate, LoopGDK and dbSynch functions. Compare this to the previous program which did not draw the dots. This program uses an infinite loop which you should never use.

Program 7-3 Moving Ball.cpp (pg 286 – 289)

This program demonstrates the game loop function LoopGDK for a simple animation. The ball moves from the bottom of the screen to the top and then starts over from the bottom.

Program 7-4 KeyDetection.cpp (pg 291)

This program is an example of detecting different arrow keys using if statements nested inside a while loop. You should NOT use a switch statement in case the user presses several keys at once. (See note pg 292)

Program 7-5 MoveThe Circle.cpp (pg 293 – 294)

This program demonstrates using dbSyncOn and dbSync functions to redraw the screen. The programmoves a circle on the screen by redrawing it each time the user presses any of the arrow keys.

Program 7-6 ResizeCircle.cpp (pg 294 – 295)

This program demonstrates using dbSyncOn and dbSync functions to redraw the screen. This program displays a circle in the center of the screen. If the user presses spacebar, the circle’s radius grows. If the user presses Ctrl and spacebar, then the circle’s radius shrinks.

Program 7-7 SpriteDemo.cpp (pg 297 – 298)

This program loads two images and makes them into sprites. The background image and the UFO image. You must creates sprites for the background image so that transparency and redrawing under the sprite works when you move it.

Program 7-8 MoveSprite.cpp (pg 299 – 301)

This program displays the background and UFO images. The game loop allows the user to move the UFO by pressing the arrow keys. Notice the sprite coordinates are passed by reference.

Program 7-9 RotateSprite.cpp (pg 302 – 304)

This program displays the space background and the UFO. The game loop allows the user to rotate the UFO by pressing the Up or Down keys. See Figure 7-8 for output samples (page 305).

Program 7-10 MissingBackground.cpp (pg 313)

This program loads the space.bmp image and the UFO.bmp image. Only the UFO.bmp image is turned into a sprite. When you run the program the space.bmp image is not displayed. See Figure 7-13 Output of Program 7-10. The next program solves this problem.

Program 7-11 MoveSprite2.cpp (pg 314-316)

This program resolves the missing background problem of the previous program by creating sprites for the background image (space.bmp) and the UFO image (ufo.bmp). See Figure 7-14 page 317 Output of Program 7-11 and compare to Figure 7-13 on page 314.

Program 7-12 PastedSpriteCopy.cpp (pg 317 – 319)

This program shows examples of pasting sprites. When you paste a sprint, you make a copy that is dependent on the orginal. When you change the original the change will apply to any pasted copy. See Figure 7-15 for the screen output (pg 319) Cloning a sprite works differently. See the next program.

Program 7-13 ClonedSpriteCopy.cpp (pg 320 – 321)

This program demonstrates cloning a sprite. It creates a UFO sprite and then makes 2 clones of the sprite. The changes to the original UFO has no effect on the clones. See Figure 7-16 for the screen output (pg 322). Pasting a sprite works differently. See the previous program.

Program 7-14 CelAnimation.cpp (pg 324 – 325)

This program uses 8 separate images for an man walking animation.

Program 7-15SpriteSheetClock.cpp (pg 328 – 329)

This program uses a sprite sheet with 8 frames for a clock animation.

Program 7-16 SpriteCollision.cpp(pg 330 – 332)

This program shows collision detection. When the program runs, it displays 2 bowling ball sprites shown in Figure 7-21 (pg 333). The sprites move toward each other until a collision is detected. When that happens, they are reset back to their original positions.

In the Spotlight: Program 7-17 The PizzaBot Game PizzaBot.cpp (pages 334 - 339)
Program 7-17 is called PizzaBot because the main character is a pizza eating robot. The robot has a sprite sheet with 3 images. The object of the game is to use the arrow keys to move the robot to the pizza slice. When the robot collides with the pizza, the Yum! image replaces the pizza slice. The program is divided into 5 functions:

  1. setUp() function seeds the random numbers generator, sets up the files for the robot using the sprite sheet, and loads the pizza and yum images.
  2. generatePizza() function displays the pizza at a random location on the screen.
  3. updateRobot() function movies the robot using the arrow keys
  4. detectCollision() function shows Yum is the robot collides with the pizza, and generates a new slice of pizza.
  5. showYum() function displays the yum image in the place of the pizza slice.

ITP 134 – Chapter 7Mrs. EatonPage 1