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 />

First, on line 52, we check to see whether our square is travelling<br />

upwards at a speed greater than 1 pixel per frame. If it is, then we<br />

multiply that value by 0.9 so it will eventually come to a point where it<br />

is travelling less than 1 pixel per second; when that happens, we set the<br />

value to 0 so that we can start falling back to the bottom of the screen.<br />

Next, our code checks whether or not our square is in the air: if it is, it<br />

will need to come back down. On lines 59-61, we check that the square<br />

is in the air and then start adding the gravity value to the playerVY<br />

value; this will make our square move back down to the bottom of the<br />

screen. Each time we add the gravity value to the playerVY value, we<br />

multiply the former by 1.1; this makes the square speed up as it falls<br />

back to the bottom of the screen, just as it would if you threw a ball in<br />

the air. Lines 63-64 reset the gravity and playerVY values when the<br />

bottom of the square hits the bottom of the screen. Lines 68-70 are fun,<br />

in that they stop the square from moving any faster left or right once our<br />

square has jumped in the air. You can’t change direction after you jump;<br />

you can only change direction when you hit the ground again, so that’s<br />

what our square does too.<br />

Above A<br />

demonstration<br />

of the varying<br />

effects of the<br />

X velocity<br />

when jumping<br />

Pygame mouse events<br />

That’s enough of the keyboard for now; it’s time for the mouse to<br />

shine. The mouse is a simple bit of kit, so the code for it is far less<br />

complicated than our keyboard code. If you copy out mouse.py and run<br />

it, you’ll see a familiar red square sitting at the bottom of the screen.<br />

Pressing your keyboard keys will do nothing this time, for this square is<br />

different. If you want to move it, you’ve got to use the mouse to pick it<br />

up. Drag your mouse over the square, hold down the left mouse button<br />

[ Taking Control of the Keyboard & Mouse ]<br />

36

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

Saved successfully!

Ooh no, something went wrong!