11.12.2015 Views

GAMES

Essentials_Games_v1

Essentials_Games_v1

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[ MAKE <strong>GAMES</strong> WITH PYTHON ]<br />

The first thing we do on<br />

each loop of our game<br />

is set three variables...<br />

only three methods and a range of variables to affect and track each<br />

bullet: move, draw, and loadImages. How do the bullets know when they<br />

are hitting something? Because each bullet created in our game is stored<br />

in the bullets list in each of our ships, we use the ships class method<br />

checkForHit to see whether or not any of the bullets hit anything.<br />

There’s no real reason for doing it this way - we could have each bullet be<br />

responsible for checking if it hit something - but it does make sense to<br />

have each ship keep an eye on whether the bullets it fired hit something.<br />

Game events<br />

Now we know what each file is responsible for in our latest game, we can<br />

start walking through how they all come together. As soon as our game<br />

is run, the global variables are set and all of the imports between lines<br />

1 and 39 are applied. Let’s take a look at our main loop starting on line<br />

90 in aliens.py. The first thing we do on each of our game loops is to set<br />

three variables: timeTicks, mousePosition, and mouseStates. The<br />

timeTicks variable keeps track of how many milliseconds have passed<br />

since we started the game. We can use this to set variables or create<br />

new objects after a set amount of time, as we do on line 128, where we<br />

create a new enemy ship after every 1.5 seconds of the game playing.<br />

mousePosition is where we store the position of the mouse in our game<br />

window. Remember, our mouse position is relative to the top-left of our<br />

Pygame window. We use the mouse to move our ship around in our game,<br />

so we need to keep a constant track of where our mouse is; storing our<br />

mousePosition at the start of each loop saves us a little time and typing<br />

if we need to check the position more than once every loop. mouseStates<br />

is where we save the ‘state’ of our mouse buttons, namely which buttons<br />

are being pressed down and which ones aren’t. We use the left mouse<br />

button to fire our weapons and start our game so having that information<br />

stored globally means we can check against one variable rather than<br />

calling pygame.mouse.get_pressed() multiple times.<br />

[ The Aliens are trying to kill me ]<br />

120

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!