Fundamentals of Game Design, 2nd Edition - Ch 1

Fundamentals of Game Design, 2nd Edition - Ch 1

L L Line CSE 420 Computer Games Lecture #6 Game Foundations Objectives Understanding the need for a graphic toolkit such as SDL

Understanding space and time in games Creating a general game loop Installing and using the pygame library Using the IDEA framework to set up a game overview Lecture #6 Game Foundations Objectives (cont.) Using the ALTER framework to manage a game loop Handling screen displays

Managing colors Moving objects on the screen Lecture #6 Game Foundations Games and Time Most programs run more slowly than the underlying computer. Games are run as quickly as possible. This is demanding on the processor and graphics capabilities. Lecture #6 Game Foundations

The Importance of Frame Rate Frame rate is the speed at which the visual display updates. A faster frame rate leads to more fluid animation and is more computationally intensive. The goal is to have a fast, consistent frame rate. Lecture #6 Game Foundations

Games and Space Games are often run in different display modes than typical programs. Each dot is a pixel. 640 x 480 and 800 x 600 pixels are common screen resolutions. The pixels are often stretched to fill the entire screen. Games often use custom user interfaces.

Lecture #6 Game Foundations Introducing the Gaming Loop Most games have the same general programming structure. It begins with initialization (setting up the computer to display game-style information). It continues with a display loop. It terminates when the user indicates (directly or by losing) the end of the game.

Lecture #6 Game Foundations Setting Up Game Resources Most games involve multimedia resources: 2D images 3D models

Background images Sound effects Resources are usually created in specialized authoring tools. Games are often constructed with temporary "placeholder" media. Lecture #6 Game Foundations Creating the Game Entities

2D games are made up of objects that move around on the screen. The objects are usually created once at the beginning of the program. Objects may be introduced to the user much later during the game play. As much preparation as possible is done before the user begins playing the game. Lecture #6 Game Foundations Building the (Almost) Endless Loop The game play itself occurs inside a loop.

The loop repeats quickly and at a consistent rate. The loop ends when the user or game situation demands an end to the game. Lecture #6 Game Foundations Frame Rate = Loop Speed The frame rate is dependant on the speed of the main loop.

Realistic animation requires the loop to happen many times a second. If theres too much computation, the game will slow down. Python games normally run at 30 FPS (frames per second). Lecture #6 Game Foundations Getting Input from the User

A game has to interact with the user; otherwise, it's an animation. Get input from the mouse, joystick, keyboard, or other devices. Discern user intention from these input devices. Get input from the system (passage of time, collision of objects). Lecture #6 Game Foundations Updating Game Entities Change entity characteristics according to input:

Speed and direction changes Damage or death of objects Boundary collisions (leaving the stage) Real change is done on invisible variables. Change will be reflected to the user via a visual update. Lecture #6 Game Foundations Refreshing the Screen

The visual display is the primary output to the user. Essentially you create a new image every frame. Erase (or partially erase) the previous position of each entity. Draw the entity in its new state or position. Display the new image to the screen. Lecture #6 Game Foundations

Introducing Graphics APIs Working with graphics and input technology is complex. APIs (Application Programming Interfaces) gather common tools. Popular Graphics APIs: DirectX (Windows 2D and 3D) OpenGL (open-source 3D)

SDL (open-source 2D) Lecture #6 Game Foundations SDL and Pygame SDL is free, powerful, multi-platform, and open-source. SDL is written in C, so it runs very quickly. Pygame is a Python wrapper to SDL. It allows everything you need for 2D gaming. Lecture #6 Game Foundations

Installing Pygame Download binaries from www.pygame.org. Our course textbook uses pygame 1.7 with Python 2.4.4. Other versions may not work in the same way. Lecture #6 Game Foundations Primary Features of Pygame

Display mechanism (screen) Surface object (images) Rect object (shapes) Input modules (key, mouse, joystick) Output modules (images, audio) Utility modules (time, transformation) Lecture #6 Game Foundations IDEA / ALTER

Framework Easy to remember Encapsulates main ideas of game loop IDEA - initialization ALTER - main loop Lecture #6 Game Foundations IDEA Import and Initialize

Display configuration Entities Action Lecture #6 Game Foundations IDEA Code See idea.py #I - Import and initialize import pygame pygame.init() #D - Display configuration screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Hello, world!") #E - Entities (just background for now) background =

pygame.Surface(screen.get_size()) background = background.convert() background.fill((0, 0, 255)) #A - Action (broken into ALTER steps) Lecture #6 Game Foundations Initialize Import the pygame module. Run pygame's initialization routine. #I - Import and initialize import pygame pygame.init() Lecture #6 Game Foundations

Display Configure the display. Set the display mode. Set screen size. Set the window caption. #D - Display configuration screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Hello, world!") Lecture #6 Game Foundations Entities

Create game entities (backgrounds, images, sounds). The background is a Surface object. Same size as screen. Convert to pygame format. Fill to change color. #E - Entities (just background for now) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((0, 0, 255))

Lecture #6 Game Foundations Action Set up the primary game loop. Action steps are detailed in the ALTER acronym Lecture #6 Game Foundations ALTER

Assign values to key variables Loop Timing Events Refresh display Lecture #6 Game Foundations ALTER Code From idea.py #A - Assign values to key variables clock = pygame.time.Clock() keepGoing = True #L - Set up main loop while keepGoing:

#T - Timer to set frame rate clock.tick(30) #E Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False #R - Refresh display screen.blit(background, (0, 0)) pygame.display.flip() Lecture #6 Game Foundations Assign Values Create a clock to manage frame rate. Set a Boolean sentry variable.

Initialize keepGoing to True. #A - Assign values to key variables clock = pygame.time.Clock() keepGoing = True Lecture #6 Game Foundations Main Loop Create a loop based on the keepGoing variable. For all code thats executed, each frame goes inside this loop. #L - Set up main loop while keepGoing:

Lecture #6 Game Foundations Timing Call clock variables tick() method. The parameter sets the games maximum frame rate. 30 FPS is typical for Python games. #T - Timer to set frame rate clock.tick(30) Lecture #6 Game Foundations

Handle Events Get all events that happened in this frame with event.get(). If any of the events are QUIT events: Set keepGoing to False. This setting will end the loop on its next cycle. Catch other events (mouse, keyboard)

here, as well. #Event Handling for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False Lecture #6 Game Foundations Refresh Display Update the background. For now, blit the background onto the screen. Set the background position to (0, 0) to completely cover the screen.

Use flip() to double-buffer. #R - Refresh display screen.blit(background, (0, 0)) pygame.display.flip() Lecture #6 Game Foundations Blitting an Image blit is a shortening of bitblit, which is a type of binary block transfer.

Its a memory technique used to quickly copy a rectangular chunk of memory to another location. Blit functionality is built into modern graphics cards. Copying an image is blitting it to a new position. Lecture #6 Game Foundations Double-Buffering

Displaying graphics to screen is a slow process. It's faster to assemble graphics in memory, then blit the resulting image to display memory. Pygame uses the flip() method to copy the background image to the display memory. This process is called double-buffering. Double-buffering reduces flicker and improves animation quality. Lecture #6 Game Foundations Colors in Pygame

Pygame (like most computing applications) uses additive color models. Colors are determined by three numbers indicating the amount of red, green, and blue light in a pixel. Each value ranges between 0 and 255 (base 10) or between 0x00 and 0xFF (base 16). Lecture #6 Game Foundations More on Color

Web developers are often more comfortable with hex color schemes. See colorViewer.py for an interactive example of colors in Python. Look at the code to preview more complex pygame programs. Use arrows to pick a color. Use spacebar to switch between decimal and hex numbering. Lecture #6 Game Foundations Moving an Object

Begin with the IDEA/ALTER framework. Add a box entity. Add variables to describe box position. Inside the loop, manipulate variables. Redraw the background. Redraw the box in a new position. Lecture #6 Game Foundations Creating the Box See moveBox.py.

Begin with a copy of idea.py. The following code is added to the Entities section: #make a red 25 x 25 box box = pygame.Surface((25, 25)) box = box.convert() box.fill((255, 0, 0)) Lecture #6 Game Foundations Setting Up Position Variables The box has variables to control its X and Y positions. The following code is also in the Entities

section: # set up some box variables box_x = 0 box_y = 200 Lecture #6 Game Foundations Moving the Box After checking events, update the box variables: Increase the box_x variable by five. This doesn't actually move the box!

The actual motion happens in the refresh step. #Events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False #modify box value box_x += 5 Lecture #6 Game Foundations Checking for Boundaries In general, whenever you change a variable,

think about boundary conditions. If the box leaves the right side of the screen, set its X value to 0. This setting causes the box to wrap around the screen. #check boundaries if box_x > screen.get_width(): box_x = 0 Lecture #6 Game Foundations Refreshing the Screen

Use the blit() method to draw the box on the screen. Use (updated) box_x and box_y variables to determine the box's position. To appear, the box must be drawn after the background. #Refresh screen screen.blit(background, (0, 0)) screen.blit(box, (box_x, box_y)) pygame.display.flip() Lecture #6 Game Foundations Discussion Questions

Why use an API such as SDL/pygame? In what ways are games approximations of normal space and time? Why learn a framework such as IDEA/ALTER? How do pygame colors relate to the Web-safe color palette? Why do modern graphics cards contain built-in bitblit functions? Lecture #6 Game Foundations Summary

You should now understand The need for a graphic toolkit such as SDL Space and time in games Creating a general game loop Installing and using the pygame library Using the IDEA framework to set up a game overview and the ALTER framework to manage a game loop

Handling screen displays and managing colors Moving objects on the screen Lecture #6 Game Foundations Next Lecture Drawing and Event Handling Lecture #6 Game Foundations References Andy Harris, Game Programming, The L Line, The Express Line to Learning; Wiley, 2007 Lecture #6 Game Foundations

Recently Viewed Presentations

  • Forest carbon Evaluation in a Community Forest Context: Case ...

    Forest carbon Evaluation in a Community Forest Context: Case ...

    Forest products resulting from the CF belong entirely to the village communities' concerned. It management involves the participation and collaboration of various stakeholders including. Aim to (i) generate income in the community (ii) Improve the living conditions of the people...
  • Defining the AA and AS: A Modest Proposal - ASCCC

    Defining the AA and AS: A Modest Proposal - ASCCC

    Discussion Defining the AA and AS: A Modest Proposal Mark Wade Lieu, ASCCC Paul Setziol, DeAnza College John Stanskas, San Bernardino Valley College Defining the AA and the AS: Why do it? Associate Degree Title 5 Regulation §§55061-55063 What is...
  • Land Planning Concepts

    Land Planning Concepts

    Steps of HIA Assessment, which is a two step process that first describes the baseline health status and then assesses potential impacts Scoping, to establish the scope of health effects that will be included in the HIA, the populations affected,...
  • Preparation - Periodic paralysis

    Preparation - Periodic paralysis

    CMAP changes following long exercise in an unaffected patient (A), a patient with hyperkalemic periodic paralysis (hyperKPP) and T704M sodium channel mutation (B), a patient with hypokalemic periodic paralysis (hypoKPP) and R528H calcium channel mutation (C), a patient with Andersen-Tawil...
  • There is Power in Unity - WordPress.com

    There is Power in Unity - WordPress.com

    [email protected] Umoja Community History Oct 2006 - Umoja I Diablo Valley College March 2007 - Umoja II Chaffey College Oct 2007 Umoja III Chabot College Summer Retreat January 2008 - BOG Recognition Umoja Consortium Four Pilot Colleges Regional Symposiums -...
  • Preparation of Zanzibar Education Sector Plan 2016-2020

    Preparation of Zanzibar Education Sector Plan 2016-2020

    Indicators for monitoring education programmes and learning achievement shall be developed (ZEP 2006, p.50-51). ... Decline of Numeracy Levels of Teachers by gender - higher % of female than male teachers in lower levels of numeracy competence.
  • Rudimentary Client-Server Message Board Ricky Landry COP5611 ...

    Rudimentary Client-Server Message Board Ricky Landry COP5611 ...

    Rudimentary Client-Server Message Board Ricky Landry COP5611 - Operating Systems Design Principles University of Central Florida April 16, 2012 Subject FSEC template
  • Unit 1 Math Review - Central Dauphin School District

    Unit 1 Math Review - Central Dauphin School District

    Unit 1 Math Review Lesson Essential Question How do I know what to study for my math test? Tally Marks Make 15 tally marks. Make 32 tally marks. Make 27 tally marks. Counting Money Count the coins below. P P...