WHEN YOU’RE PLAYING computer games on your PC, one of the ways you can give the game commands is via the keyboard. You use different keys to give different commands—for example, you usually use the W, A, S and D keys to move the player around the game.
In this adventure you’ll learn how to use the keyboard with PyGame
. You’ll also make a game in which, for the first time, you’ll move a player around the window. Okay—your player is just a dot on the screen at this stage, but it’s a good start! As the program develops throughout the adventure, you’ll add extra features like a ball that your player can “kick,” a goal and a points system.
The gameplay and graphics in this game are very simple, so during the adventure you may want to add more features to the game, like better graphics. Try using some of the things you learned in Adventure 5 to add that little bit extra to the game. You can also come back to the game and improve it after you’ve learned more in later adventures. You’ll be learning lots in the sound adventure in Adventure 9, for example, so you can add sound to the game once you know how to do that.
Using the keyboard with a PyGame
program is very straightforward. When you press a key on PyGame
it adds it to a list of the keys that you’ve pressed. By checking which keys are in this list, you can make your program do different things.
Let’s have a look at an example to understand this better:
Adventure 6
. Save the program in the folder as keyboardExample.py
.import pygame
pygame.init()
# Window setup
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
# Game loop
done = False
while not done:
keys = pygame.key.get_pressed()
# Display a message when the w key is pressed
if keys[pygame.K_w]:
print "Hello"
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
clock.tick(32)
pygame.quit()
With PyGame
you can use every key on the keyboard to control your programs. The letter keys are straightforward to work out. As you just did, all you have to do is replace the last letter of the code pygame.K_t
with the letter you want to use. For example, if you wanted to use the x key, the code would be pygame.K_x
. You don’t have to stick to the letters though! Table 6-1 shows you a few of the other keys you can use and how to do it.
Table 6-1 Keyboard Control Codes in PyGame |
|||
Key |
|
Key |
|
1 |
|
Escape |
|
Backspace |
|
Right Shift |
|
Space |
|
Left Shift |
|
Enter |
|
Up |
|
Now you’re going to start making a little game in which you’ll use the keyboard to move a player around the screen. The player won’t be that complex—just a red dot on the screen. If you want to spend more time on this, why not think about what you learned in Adventure 5? You could always combine some shapes to make a much cooler picture of your player and use this instead of the red dot.
Figure 6-2 shows what the finished game will look like.
Once you’ve got the movement set up with the keyboard, you’ll be adding more things to the game, like a ball and a goal. And an explosion!
This first part of the program will only move the player upwards. You’ll add the code to move it in other directions afterwards.
Let’s get going!
movementGame.py
in the Adventure 6
folder.PyGame
program:
import pygame
pygame.init()
# Window setup
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
# player position
x = size[0] / 2
y = size[1] / 2
# colours
red = pygame.color.Color('#FF8080')
blue = pygame.color.Color('#8080FF')
white = pygame.color.Color('#FFFFFF')
black = pygame.color.Color('#000000')
# Game loop
done = False
while not done:
screen.fill(black)
keys = pygame.key.get_pressed()
#player movement
if keys[pygame.K_w]:
y -= 1
# draw player
pygame.draw.circle(screen, red, [x, y], 6)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
clock.tick(72)
pygame.quit()
The game wouldn’t be very good if your player could only move upwards. Time to fix that. In this part of your adventure, you’ll add some code to enable the player to move up, down, left and right.
This will work when you press the w, a, s and d keys, which are normal movement controls for most modern computer games.
Let’s go!
movementGame.py
is not already open, open it now.#player movement
comment and the if
statement that checks the w key is pressed. It should look like this:
#player movement
if keys[pygame.K_w]:
y -= 1
if keys[pygame.K_s]:
y += 1
if keys[pygame.K_a]:
x -= 1
if keys[pygame.K_d]:
x += 1
Excellent! You’ve got a bit of movement in the game. But wait—at the moment the player disappears whenever you move them offscreen. We can’t have that. You’ll fix this in the next part of the program.
At the moment, when you reach the edge of the display the player will disappear out of sight. This is because the player’s co-ordinates, which are stored in the x and y variables, are bigger or smaller than the size of the screen.
This is quite straightforward to fix. To do it you’ll add a function that checks whether the player is off the screen. If they are, it will teleport them to the opposite side of the screen. In other words if the player disappears off the top of the screen, they’ll reappear at the bottom and vice versa. If they move off the right of the screen, they’ll reappear on the left. Here’s how:
movementGame.py
program open. If you don’t, now’s the time to open it.# Game loop
done = False
def checkOffScreenX(x):
if x > size[0]:
x = 0
elif x < 0:
x = size[0]
return x
def checkOffScreenY(y):
if y > size[1]:
y = 0
elif y < 0:
y = size[1]
return y
# draw player
pygame.draw.circle(screen, red, [x, y], 6)
# Check off screen
x = checkOffScreenX(x)
y = checkOffScreenY(y)
Now that you have a player that can move around the game, it would be great to have something they can interact with. In this part of the adventure, you’ll add a ball to the game for the player to kick around. You’ll later add a goal for the player to kick the ball into.
Your first task is to set the ball at a random position in the game and draw it:
movementGame.py
program, add this line of code to the first line of the program. This will let your program use random numbers:
import random
# player position
x = size[0] / 2
y = size[1] / 2
# ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])
# draw player
pygame.draw.circle(screen, red, [x, y], 6)
# draw ball
pygame.draw.circle(screen, blue, [ballX, ballY], 6)
At the moment, when your player kicks the ball it doesn’t do anything. To fix this you’re going to add some code that checks whether the player is near the ball and causes a small explosion if they are:
movementGame.py
program find the checkOffScreenY()
function. Below that function add this function that will check if the player is touching the ball:
def checkTouching():
"""Causes a mini explosion if the players are touching"""
global x
global ballX
global y
global ballY
# Check if player and ball are touching
if -10 < y - ballY < 10 and -10 < x - ballX < 10:
#draw an explosion
pygame.draw.circle(screen, white, [x, y], 15)
xDiff = x - ballX
yDiff = y - ballY
# check if ball is on edge of screen
if ballX == 0:
xDiff -= 5
elif ballX == size[0]:
xDiff += 5
if ballY == 0:
yDiff -= 5
elif ballY == size[1]:
yDiff += 5
# move the ball and player
x += xDiff * 3
ballX -= xDiff * 3
y += yDiff * 3
ballY -= yDiff * 3
# draw player
pygame.draw.circle(screen, red, [x, y], 6)
# Check if player is touching the ball
checkTouching()
You may notice that if you kick the ball to the side of the screen gets stuck. To fix this, you can use the functions on the ball’s position variables to check whether the player is offscreen. Let’s do this now:
# Check off screen
x = checkOffScreenX(x)
y = checkOffScreenY(y)
ballX = checkOffScreenX(ballX)
ballY = checkOffScreenY(ballY)
Now that the player can kick the ball around the screen, you’re going to add a goal to the game so that the player has something to kick it at and score points. The program will draw a goal at the center of the screen and check whether the player has kicked the ball into the goal. Figure 6-8 shows what the goal will look like.
# ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])
# Goal position
goalX = size[0] / 2 - 10
goalY = size[1] / 2 - 10
goalW = 20
goalH = 20
# points
points = 0
screen.fill(black)
#Draw the goal
pygame.draw.rect(screen, white, (goalX, goalY, goalW,
goalH))
# Check ball is in goal
if goalX <= ballX <= goalX + goalH and goalY <= ballY
<= goalY + goalH:
points += 1
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[0])
Fantastic! You’ve created a program in which a player can score goals and score points. But how do you know how many points they’ve scored? Here’s how to create a display for the points:
# Draw points
for point in range(points):
pointX = 0 + point * 5
pygame.draw.rect(screen, white, (pointX, 3, 4, 7))
pygame.quit()
, add the following line of code:
print "Total points: " + str(points)
Save the program and run it. What happens? Whenever you score a goal, a small white line, one for each point, should appear in the top-left of the screen (see Figure 6-9). Finally, when you exit the window, your total points will be printed to the Python shell (see Figure 6-10).
At the moment the game does everything it needs to. Not very challenging though, is it? And it goes on forever! Why not add excitement by adding a time limit?
# Game loop
done = False
# get current time
timeStart = pygame.time.get_ticks()
clock.tick(72)
# Check elapsed time
timeNow = pygame.time.get_ticks()
if timeNow - timeStart >= 60000:
done = True
Python Command Quick Reference Table |
|
Command |
Description |
|
This function in |
|
The keypresses in the |
|
Global variables are used in functions so that a function can change the value of a variable that was created outside of the function. |
|
Range checks check whether one value is between two other values. If the value is between the other two numbers, it evaluates to |
Achievement Unlocked: Skilled creator of a game using PyGame
and the keyboard.