Introduction to Game Programming Lesson 4 Lecture Notes

Similar documents
""" idea.py simplest possible pygame display demonstrates IDEA / ALTER model Andy Harris, 5/06 """

The Stack, Free Store, and Global Namespace

Introduction to Game Programming Lesson 5 Lecture Notes, Part 1: The draw Module

PyGame Unit ?

PYTHON NOTES (drawing.py and drawstuff.py)

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=rvrkt-jxvko

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

Linked Lists. What is a Linked List?

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

Multimedia-Programmierung Übung 6

SPRITES Moving Two At the Same Using Game State

MITOCW watch?v=se4p7ivcune

MITOCW watch?v=kz7jjltq9r4

MITOCW watch?v=flgjisf3l78

BEGINNER PHP Table of Contents

pygame Lecture #5 (Examples: fruitgame)

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Smoother Graphics Taking Control of Painting the Screen

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Intro. Scheme Basics. scm> 5 5. scm>

Multimedia-Programmierung Übung 5

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

CHAPTER 1. Command Arguments Description Example. Prints something to the console. A value can be text in quotes or a variable name.

slide 1 gaius Python Classes you can use theclass keyword to create your own classes here is a tiny example of a class

Variables One More (but not the last) Time with feeling

MITOCW ocw f99-lec07_300k

Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09

Text Input and Conditionals

MITOCW watch?v=4dj1oguwtem

MITOCW ocw f99-lec12_300k

The following content is provided under a Creative Commons license. Your support

contain a geometry package, and so on). All Java classes should belong to a package, and you specify that package by typing:

Lab 2: Conservation of Momentum

The following content is provided under a Creative Commons license. Your support

Coursework Lab A. Open the coursework project

The following content is provided under a Creative Commons license. Your support

PROFESSOR: So far in this course we've been talking a lot about data abstraction. And remember the idea is that

What's the Slope of a Line?

6.001 Notes: Section 15.1

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Post Experiment Interview Questions

CircuitPython 101: Working with Lists, Iterators and Generators

The following content is provided under a Creative Commons license. Your support

append() function, 66 appending, 65, 97, 296 applications (apps; programs), defined, 2, 296

Skill 1: Multiplying Polynomials

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Python Games. Session 1 By Declan Fox

Intro. Classes & Inheritance

(Refer Slide Time: 06:01)

Lesson 1. Importing and Organizing Footage using Premiere Pro CS3- CS5

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

6.001 Notes: Section 8.1

6.001 Notes: Section 17.5

The following content is provided under a Creative Commons license. Your support

(Refer Slide Time: 02.06)

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

Lesson 6: Manipulating Equations

Note: Please use the actual date you accessed this material in your citation.

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CS12020 for CGVG. Practical 1. Jim Finnis

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

Transcriber(s): Aboelnaga, Eman Verifier(s): Yedman, Madeline Date Transcribed: Fall 2010 Page: 1 of 9

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

How to Improve Your Campaign Conversion Rates

Instructions for Crossword Assignment CS130

Notes from the Boards Set # 5 Page

Quiz 3; Tuesday, January 27; 5 minutes; 5 points [Solutions follow on next page]

Intro. Speed V Growth

It Might Be Valid, But It's Still Wrong Paul Maskens and Andy Kramek

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Load your files from the end of Lab A, since these will be your starting point.

Slicing. Open pizza_slicer.py

Pyganim Documentation

Java Programming. Computer Science 112

P1_L3 Operating Systems Security Page 1

AN INTRODUCTION TO SCRATCH (2) PROGRAMMING

B - Broken Track Page 1 of 8

Excel Basics Fall 2016

Programming with Python

The following content is provided under a Creative Commons license. Your support

Instructor (Mehran Sahami):

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

Pygame In a Few Minutes

3.7. Vertex and tangent

MITOCW watch?v=9h6muyzjms0

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Video Games. Writing Games with Pygame

Combinatorics Prof. Dr. L. Sunil Chandran Department of Computer Science and Automation Indian Institute of Science, Bangalore

There we are; that's got the 3D screen and mouse sorted out.

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

PyGame Sprites. an excellent turorial exists for PyGame sprites here kai.vm.bytemark.co.uk/ piman/writing/spritetutorial.shtml.

6.001 Notes: Section 6.1

Working with Objects. Overview. This chapter covers. ! Overview! Properties and Fields! Initialization! Constructors! Assignment

Shadows in the graphics pipeline

Transcription:

Introduction to Game Programming Lesson 4 Lecture Notes Learning Objectives: Following this lecture, the student should be able to: Define frame rate List the factors that affect the amount of time a game cycle takes Define pixel, screen resolution List the work that is accomplished inside a gaming loop List the game resources and give one reason they are set up before the gaming loop Relate the frame rate to the gaming loop List what happens at the following stages of the game loop: getting input from the user, updating game entities, refreshing the screen Define the import and initialize step of the framework and give examples of code that would go here Define the display configuration step of the framework and give examples of code that would go here Define the entities step of the framework and give examples of code that would go here Define the assign values step of the framework and give examples of code that would go here. Define the main loop step of the framework and give examples of code that would go here Define the timing step of the framework and give examples of code that would go here Define the handle events step of the framework and give examples of code that would go here Define the refresh step of the framework and give examples of code that would go here Define the terms blit, double-buffering, and flip Define RGB color and give the range of values for R,G, and B; be able to give a rough idea of a color given RGB values Motivation (This needs no motivation.) We're going to start using Pygame now, which is the game programming library that gives us graphics, audio, collision handling, and ways to process input, among other functions. Frame rate Slide #5 Frame rate is the speed at which the visual display updates. This is measured in frames per second. It is important to maintain a constant frame rate in a game. A game executes in a loop that runs over and over. Each loop, the game processes input from the user, makes the necessary adjustments to the data of the game and the display, and redraws the display. The frame rate must allow enough time for the slowest processing to occur, and it must slow the game down if there is less processing so it runs at a constant speed. Bring up tetrash.py Copyright 2010 Margaret Burke. All rights reserved. 1

This is an example that is more complicated than what we're going to be doing this chapter. Even the stuff in this chapter might make your head swim, learning new terminology and wondering what is pygame and what is python and what everything is doing. But I want to show you this example so you have an idea of what the gaming loop is all about so we can talk about timing. Go over and explain the code in terms of an image drawn at a location, each cycle the image is updated (just dropped) and also based on user input, then redrawn. So the speed at which the game repeats is the frame rate. That is how frequently the game is updated. TV has a frame rate of 30 frames/sec, and 30-60 is a good range for a game. Less than 10 frames/second and your game will look like choppy. Change to block_y+=10, show at 30 frames/sec, then change to 5 frames/sec, see the choppiness. (This starts at block_y+=2, 30 frames/sec.) So I'm going to have a frame rate of 30 frames/sec for all of our games. You don't want it to be so fast that when the drawing gets complicated, you can't get all the drawing done in time. So basically, what's happening is the processor is doing these calculations, including getting what's ready to draw to the screen drawn on a surface. More calculations take more time. Less calculations take less time. But you don't want it to run quickly sometimes and more slowly other times. So by setting the frame rate, you basically are having it do its computations, then letting it wait around until the frame rate time runs out, if there's any extra, so that the frame rate is consistent. The screen Let's talk a little about the screen. http://www.amitbhawani.com/blog/wp-content/uploads/2009/10/lcd-monitor-resolution.gif Copyright 2010 Margaret Burke. All rights reserved. 2

Logically and physically, our monitors are composed of picture elements, or pixels, that are arranged in a grid. The higher the resolution, the more pixels in the grid. We'll talk about this in more detail in Chapter 5. For now what I want to mention is that we're going to create our game in a window, with our own interface, or way of interacting with the user. The smaller the window, the less time it will take to draw, and the faster our game will be. Let's talk about how those pixels are arranged on the screen, though. http://inetjava.sourceforge.net/lectures/part2_applets/inetjava-2.1-2.2-introduction-to-awt-and- Applets_files/image001.gif Okay, so this is different from the Cartesian coordinate system you learned in geometry in that the y coordinate increases as you move down the screen. That's just something to keep in mind. If we want something to move down the screen, we increase its y coordinate, we don't decrease it. If we want something to move right, we increase its x coordinate. If we want something to move left, we decrease its x coordinate. Game structure On to the details of the structure of the game, which I talked about briefly when I showed you tetrash.py and discussed timing. Slide 8, 9 Computer programs manipulate data. We have talked about the kind of data that's stored for a game. We can call this the game state. Before the gaming loop, all of these objects need to be created. For example, images and sounds need to be loaded in. These are called game assets. It takes time to load the assets in, so this is done once, Copyright 2010 Margaret Burke. All rights reserved. 3

before the loop, and then the assets can be accessed quickly in the loop. This is what's happening while a game is "loading." Because games need to be fast, you want to do as much as possible before the game begins. Slide 10, 11, 12 In the gaming loop, the program gets input from the user, alters the game state based on the user's actions, and redraws the screen. This all happens at the frame rate that you set. So one loop of the game happens each frame. Slide 13, 14 Things that can happen during the loop include the user changing the speed or direction of motion, collisions, things exploding or changing size or moving out of bounds. So you update your data. In other words, you change your variables. Let's go back to tetrash.py and look at the code for a minute. I have the block, which has the variable name "block," and this is a type we haven't seen yet, which is a pygame type, which is a Surface. A Surface in pygame is the type we use for images. But then there are two variables of an Integer (int) type, block_x and block_y, and these are the upper left coordinates of the block. Now down here is the game loop (while keepgoing:), and in the game loop I look first for user input, and what I'm doing here is checking for key presses. Cold call What happens if the user presses the Subtract 10 from block_x left arrow key (Indicate code)? Cold call What happens if the user presses the right arrow key (Indicate code)? Add 10 to block_x Now in the next line I'm doing something a little fancier, once again I'm using pygame and I'm using a pygame method to rotate the block if the user presses the up key. But after we're done checking events, which is how we get user input, then we update the rest of the game state. Cold call What's happening here? Adding 2 to an integer, (block_y=block_y+2) adding 2 to the y Hands And can anyone figure out the next line? coordinate Checking for bottom screen boundary Right. So if the user presses an arrow key, I'm updating an integer variable. Just adding or subtracting 10 from it. After that I'm adding 2 to the y variable. So how does it happen that the block appears to move on the screen, both down automatically, and to the right or left if the user presses a key? Copyright 2010 Margaret Burke. All rights reserved. 4

Well, it's the next part of the code. I have a teal image, just a plain teal background, that happens to be the size of the window. And first I copy that to the screen. Background and screen are just two images. So I'm copying the background image to the screen image at 0,0, which completely covers the screen, because they're the same size. Then I copy the block onto the background. And I copy it to the coordinates that we just changed. Cold call So if the old y coordinate was 20, 22 what's the new y coordinate? Cold call And if the old x coordinate was 100 and the use pressed the left arrow, what's the new x coordinate? 90 Right. So the last time the block was copied to the screen, it was copied at 100,20. This time it's copied at 90,22. This happens quickly, 30 frames per second, so it appears the block has moved. We're going to go into this loop in great detail and I'm going to explain everything that's in there. I want you to understand the general idea of how it works, first. Slide 15, 16, 18 Okay, so I wouldn't want to do this without pygame. Games like that little tretrash thing I wrote would've taken days to write without an API, or application programming interface that is designed specially for writing games. We're going to use the Pygame library, which is built on top of SDL (Simple DirectMedia Layer) and allows us to work with graphics, sound, and sprites. This is 2D. Hopefully you have already installed Pygame at home. It's very simple. I believe I have a video on the website in which I show you the install I did last Thanksgiving. You can attempt another configuration if you like. That configuration took me days to put together in such a way that I could build a game for distribution. Getting Python and Pygame to work together is easy; getting a configuration and build file that will allow you to build for distribution is not so easy. Slide 19, 20, 26 / idea.py For the rest of this lesson we're going to go over the gaming loop in detail. Then we're going to work on a moving box program that is the basis for your project. There isn't much you can do for a lab until we start working on the moving box code. So the author has come up with this mnemonic for remembering the parts of the gaming loop, and it's IDEA/ALTER. I used to make my class memorize this and write it down for the Lesson 4 quiz. You'll note we don' t have a Lesson 4 quiz. You should still memorize this. Read slide 20 and then turn to the code and go over the parts. Copyright 2010 Margaret Burke. All rights reserved. 5

import: Remember before we had to import the random library. We do any imports at the top of the file. So we import pygame here, and if we were using a random function we'd import random here too, and if we're using any other libraries, such as the math library, we'd import those here as well. Okay, and then luckily "initialize" also begins with an i. Think of it as i 2. You need to initialize the pygame module. Display. This is all new. We're not running in the console window any more; so we have to set up our own graphical interface. If you're going to have any text telling the user how many lives she has left, if you're going to have menus, buttons, etc., you're going to have to set them up yourself. For now we're just going to look at the simplest possible program and then we'll slowly build on it, and that's going to be new enough. So the first thing to know is that a Surface is a new data type. Cold call What are the data types we've seen int, float, str, list before? Good. Okay and remember that string and list types had libraries of methods that we could call. Well Surface is the first pygame type we're going to look at, and it's the Pygame graphics type. So if we have an image that we want to load in, or if we want to just draw using Pygame's drawing methods (which we'll learn in the next lesson), then we create a Surface variable. Now there are different ways to make a Surface. The first we see is this one: screen = pygame.display.set_mode((640, 480)) Anything you see that is part of pygame, you can look up in the pygame documentation. First, what is display? This is the object that we're sending the set_mode message to. This module offers control over the pygame display. Pygame has a single display Surface that is either contained in a window or runs full screen. Once you create the display you treat it as a regular Surface. Changes are not immediately visible onscreen, you must choose one of the two flipping functions to update the actual display. Okay, so the display is basically the window that your game runs in. You can draw to it like a regular Surface, and eventually you will use a flipping function so that it's shown to the user. So you're drawing on it backstage and then when you're ready, you show it to the user. Now let's look at set_mode: Copyright 2010 Margaret Burke. All rights reserved. 6

http://www.pygame.org/docs/ref/display.html#pygame.display.set_mode: pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface This function will create a display Surface. The arguments passed in are requests for a display type. The actual created display will be the best possible match supported by the system. The Surface that gets returned can be drawn to like a regular Surface but changes will eventually be seen on the monitor. If no resolution is passed or is set to (0, 0) and pygame uses SDL version 1.2.10 or above, the created Surface will have the same size as the current screen resolution. If only the width or height are set to 0, the Surface will have the same width or height as the screen resolution. Okay. So this returns a Surface. It is that important Surface that is going to be the display the user sees. Now this is on the right hand side of an assignment statement. Cold call So the Surface that gets returned is screen going to be stored in what variable? Right. So when this is done, screen is a Surface variable, something that can be drawn to like a regular Surface, but that will eventually be seen on the monitor. Okay, and what's next is set_caption, which sets the text in the title bar. So that sets up the Display, which is the "D" in IDEA. On to E for Entities. This is where you create all of the assets that are in your game. I guess if he had called it "assets" then it would've been IDAA. But we should really use the terminology that's used in the industry. So if you have sounds and images and other data structures, you create them here. Looking at the very simple idea.py, all he creates here is the background, which is the Surface that he copies to the screen eventually. I remember finding this confusing when I first read this chapter, I don't know if you're finding it confusing. But the background is just one picture. It gets copied to the screen and then the other things will get copied on top of it. So it's just a picture. In this case, it's a plain obnoxiously teal rectangle. So in this case, the Surface is created in a different way. Any time you create an image, you're going to create a Surface. That's an image variable. So he creates a Surface by using pygame.surface and passing in a size. He wants the Surface to cover the whole screen, so he passes in screen.get_size(). This might be confusing. get_size is a method of a Surface. So similar to calling append for a list, we can call get_size for a Surface and we get back the size of the image. That returns (width, height). In fact, I'm going to add a line to print that to the console so we can see what gets returned from that: Copyright 2010 Margaret Burke. All rights reserved. 7

print screen.get_size() (Then execute.) Okay? So let's look at Surface creation methods. These are called Constructors, because they create a variable of this type: http://www.pygame.org/docs/ref/surface.html pygame object for representing images pygame.surface((width, height), flags=0, depth=0, masks=none): return Surface pygame.surface((width, height), flags=0, Surface): return Surface So it looks like you always must pass in what's called a tuple, which is variables enclosed in parentheses, with width first and then height. A tuple is an immutable list. So it's a read-only list. There are no tuple methods, and you use parentheses and not brackets, but otherwise it's the same. You can index it and slice it. http://diveintopython.org/getting_to_know_python/tuples.html Now he's using a graphics method for Surfaces, called fill, to fill the background Surface with a color. Okay, that gets us past the setting-up part of IDEA. The next part is "A" for "Action," and that's when we have the ALTER part of the mnemonic. This is the game loop now. Slide 26 / idea.py Okay, let's start with variables we need to manage the loop. First the clock, which will be used to set the frame rate. Then a Boolean variable, which will be used to control loop execution. When keepgoing is False, we'll stop the game. So then the game loop, which is a while loop. So while keepgoing is True, this loop will execute. Let's see what's in there: Okay, tick the clock. This is Timing. There are other ways to keep the frame rate constant in pygame, but this is the one we use in this class. You are welcome to read about and try other methods. This one has worked fine for our purposes, but I understand it's not always accurate on all platforms, according to the pygame documentation. Okay, the next part is really important, not just for this class, but if you are going to learn any kind of graphical user interface programming. All graphical user interfaces execute in an event loop. That's really what this gaming loop is. An event is something created by the system when the user accesses input hardware, and passed to your program. The system digests it a little bit before it gets passed to you, so you only have to deal with hardware events that have something to do with your program and that have been put into an Event object that you can look at and work with. Events are very cool. Copyright 2010 Margaret Burke. All rights reserved. 8

So we'll talk about events in more detail in the next lesson. For now, you get an event from pygame and you look at its type. The system puts events in a queue for us and we're just pulling the events out of the queue, looking at the type, and handling the ones we're interested in. For example, in the tetrash.py game, note that 'm only interested in keydown and quit events, and in the case of keydown events, I only deal with three keys. (Pull up tetrash.py.) We're only interested in quit events right now, so we set keepgoing to False if the user has chosen to quit the game. Setting KeepGoing to false will get us out of the loop, so we know this loop can end. List of event types here: http://www.pygame.org/docs/ref/event.html Last part! "R" for Refresh display. Okay, so this is where we take everything we've done in the background and show it to the user. Here we've done nothing at all, so we just copy the background to the screen and then call display.flip, which takes the screen and shows it to the user. One thing I want to mention is pygame.quit(). If you don't put this in, you won't be able to run your games from IDLE. Two students discovered this last semester. Until then, I thought you couldn't run your program in IDLE, because that's what the text says. Slide 33, 34 Explain double-buffering and bit block transfer. Look at tetrash.py again just to show a little bit more being done in the Refresh part. Slide 35, 36 Talk about color. Go to http://www.colorpicker.com/ Okay, so you can see in this idea.py program we set a background color. So one thing you can do is download this program from the class website and play with the color there. It's something. Moving Box So we're going to plow through, and then the rest of the lesson you can work on the lab, which is designed to help you with your project. Let's add a moving box to this idea.py program. Cold call So any graphics that we're going to Surface add are going to be of what type? Cold call Right, and we have a line of code where we create a rectangular Surface variable in this code. What Background=pygame.Surface Etc. Copyright 2010 Margaret Burke. All rights reserved. 9

Cold call Hands line is that? In what part of IDEA ALTER would we create the box we're going to move around? Does anybody want to attempt a line of code to create a box? Entities See below, for example #E - Entities (just background for now) background = pygame.surface(screen.get_size()) background = background.convert() background.fill((0, 125, 130)) box=pygame.surface((25,25)) box.fill((255,0,0)) Great, now we have a box. So suppose we want the box to start about mid-way down the screen on the left, and then we want the box to move to the right until it reaches the right edge, and then wrap around so it starts at the left again. (Run Andy Harris' movebox.py) Okay, so let me tell you what you need to know -- you need to know how to get the edges of the screen. We have screen.get_width() and screen.get_height(). Cold call And screen.get_width() will give us Right edge what edge? Cold call And screen.get_height() will give us Bottom edge what edge? Cold call And what is the left edge? 0 Hands And the top? 0 Okay, good! That's everything you need to know to program this. Let's do it. Hands Write code to move the box. They work on labs. Copyright 2010 Margaret Burke. All rights reserved. 10

""" movebox.py illustrates basic motion in the IDEA/ALTER framework moves a rect across the screen """ #Initialize import pygame pygame.init() #Display screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("move a box") #Entities #yellow background background = pygame.surface(screen.get_size()) background = background.convert() background.fill((255, 255, 0)) #make a red 25 x 25 box box = pygame.surface((25, 25)) box = box.convert() box.fill((255, 0, 0)) # set up some box variables box_x = 0 box_y = 200 #ACTION #Assign clock = pygame.time.clock() keepgoing = True #Loop while keepgoing: #Time clock.tick(30) #Events for event in pygame.event.get(): if event.type == pygame.quit: keepgoing = False #modify box value box_x += 5 #check boundaries if box_x > screen.get_width(): box_x = 0 #Refresh screen screen.blit(background, (0, 0)) screen.blit(box, (box_x, box_y)) pygame.display.flip() pygame.quit() Copyright 2010 Margaret Burke. All rights reserved. 11