© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_11

11. Developing a Game

Kevin Wilson1  
(1)
London, UK
 

To start creating your own games using Python, you’ll need to use the pygame module. This module isn’t bundled with standard distributions of Python, so you’ll need to install it before you start.

Pygame is a library of Python modules designed for writing computer games. Pygame adds functionality to create fully featured games and multimedia applications using the Python language.

This chapter will cover the basic modules and functions that Pygame provides. We’ll use these functions to create a very simple interactive game

Installing Pygame

To install the module, open a command prompt. Make sure you run this as an administrator. On the command prompt, type
pip install pygame

Once you press Enter, the install will begin.

A command prompt indicates the Microsoft windows version. Pip install pygame is typed in the C drive line.

Allow the pip utility to download and install the module.

A command prompt depicts the Microsoft windows version and indicates that the pip utility is being downloaded and the pygame module installed.

Once the process is complete, you can start using pygame.

Opening a Window

The first thing you’ll need to do is import the pygame module :
import pygame
Initialize pygame using the .init() method:
pygame.init()
Open a window. This sets the window size 640 pixels wide by 480 pixels high. This could also be 800x600, 1920x1080, and so on.
gamewindow = pygame.display.set_mode((640,480))
Set the window’s title. This is the title that appears in the title bar of the window.
pygame.display.set_caption("Game Window")
You should always end your pygame scripts with the .quit() method:
pygame.quit()

Let’s take a look at the program so far.

A window has a code for importing pygame. The lines indicating the creation of the game window and the setting of the window title are boxed.

If you run this program , the game window will initialize, open, and then immediately close. This is fine since there is no other code to execute.

Adding an Image

Let’s add an image to the game window. This is going to be our character in the game. In this case, we’re going to use a space rocket. We can add the image load statement to our program.
sprite = pygame.image.load('rocket.png')
Paste the image (sprite) onto the game window using the .blit() method, and assign the initial position on the screen (x, y):
gamewindow.blit(sprite, (x,y))
Update the display to show the image:
pygame.display.update()

Let’s take a look at the program .

A window has a code for adding an image to a game window. Lines for loading and assigning to sprite, and updating the game window display are boxed.

The Game Loop

Now, let’s get our rocket ship to actually do something. To do this, we need to create a game loop to draw our sprites, update the screen, and keep the program running.

We can take the following two statements and add them to our game loop. For this bit, we’ll use a while loop.
gamewindow.blit(sprite, (x,y))
Update the display to show the image:
pygame.display.update()
Put these inside the while loop:
while running == 1:
    gamewindow.blit(sprite, (x,y))
    pygame.display.update()
We’ll also need to initialize some variables – x and y, the initial position on the screen, and running – to indicate whether the program is running or not:
running = 1
x = 250
y = 280

Let’s take a look at the program.

A code for creating a game loop. The lines for initializing variables, adding images to a game window, and updating the game window display are boxed.

The Event Loop

In this simple game, we want the rocket ship to move left and right when the user presses the left and right arrow keys on the keyboard. To do this, we need something to handle these events.

To do this, we can put a for loop inside our while loop (the game loop). We’re monitoring for each event that occurs. You can use the .get() method to read each event.
for event in pygame.event.get():

Now inside the for loop, we need some selection depending on which key is pressed. We can use an if statement for this.

First, we need to check whether a key has been pressed:
if event.type == pygame.KEYDOWN:
Inside this if statement, we need to identify which key has been pressed. You can use another if statement.
if event.key == pygame.K_LEFT:

We do the same for all other keys we’re going to use. Just add elif statements to the if statement.

Let’s take a look.

A code for setting movements for an image. Some lines are boxed which include for, if, and elif event statements for image movements.

Now, when we run the program , you’ll see your rocket move left when you press the left key and right when you press the right key.

A game window has an image of a rocket ship on top, and upward, downward, leftward, and rightward arrow keys below.

You’ll also notice something else. The image repeats on the screen. To fix this, you need to clear the screen (refresh) each time you move the object. You can use
gamewindow.fill((0,0,0))

This returns the screen to black at the end of each iteration of the game loop (while loop).

It is also good practice to include a quit event in your event loop, so the program terminates gracefully:
if event.type == pygame.QUIT:
    running = 0

This will set our running variable to 0, meaning the game loop will terminate and the program will close. This event will happen when you click the close icon on the top right of the window.

Let’s take a look at the program so far.

A window has a code for an event loop. It includes lines for initializing variables, for, if, and elif event statements for image movements.

You’ll also notice that the rocket doesn’t move when you hold the key down. This is because the key-repeat feature is turned off. To turn this on, add the following line before your game loop:
pygame.key.set_repeat(1, 25)

The first parameter is the delay before the key event is repeated. The second parameter is the interval between repeats.

Shapes

You can add shapes such as circles, ellipses, rectangles, and other polygons.

To draw a rectangle, use the .rect() method. Specify the surface or window you want to draw on, the color, and then specify the x and y position, followed by the width and length of the rectangle.
pygame.draw.rect(gamewindow, colour,
    (x, y, width, length), thickness)
To draw an ellipse, use the .ellipse() method. When drawing an ellipse, you’re actually drawing it inside an invisible rectangle. This is why you specify width and length when drawing your ellipse.
pygame.draw.ellipse(gamewindow, colour,
    (x, y, width, length), thickness)
To draw a circle, use the .circle() method. Specify the surface or window you want to draw on, the color, and then specify the x and y position, followed by the radius of the circle.
pygame.draw.circle(gamewindow, colour,
    (x, y), radius, thickness)

Have a look at shapes.py.

A window has a code for adding shapes with lines for drawing a circle, ellipse, and rectangle, boxed. A game window has images of the shapes mentioned.

Basic Animation

To demonstrate basic animation, we’re going to move our ufo object on the screen.

First, we need to load in our image. You can do this using the .load() method as we’ve done before.
ufo = pygame.image.load('ufo.png')
Now, because an image is loaded onto a surface object by default, we can’t move it or manipulate it. To get around this, we assign the image to a rectangle. You can do this using the .rect() method .
ufo_rect = ufo.get_rect()
We also need to define some speed and direction variables. We can do this with a list. This is a list containing the [x, y] coordinates on the screen (speed[0] is x, speed[1] is y).
speed = [10, 0]
To move the object, use the .move_ip() method :
ufo_rect.move_ip(speed)

Let’s take a look at the program. Have a look at anim02.py.

A code for basic animation. Boxed lines include set horizontal by vertical list, load u f o image, assign an image to a rectangle for positioning, and move u f o.

Now, when you run this program, the ufo will fly from left to right across the screen.

A game window has an image of a boxed u f o on the upper left. A rightward arrow is labeled, speed, 0, and a downward arrow, speed, 1.

Because we set speed = [10, 0], this means we move our ufo ten pixels along the x axis each time we execute ufo_rect.move_ ip(speed) in the game loop.

If we set speed = [0, 10], this means we move our ufo ten pixels along the y axis each time we execute ufo_rect.move_ ip(speed) in the game loop.

Try changing the values in the program anim02.py and see what happens:
speed = [??, ??]

Try larger values.

Let’s take our program a step further. Let’s make the ufo bounce around the screen.

To do this, we need to check whether the left edge, right edge, top edge, and bottom edge of the ufo_rect go beyond the edges of the screen. We can use if statements for this.

If the left edge of the ufo goes off left edge, reverse x direction.

A game window has an image of a boxed u f o on the extreme left with the number 0 on top of it.

To reverse the direction , all you need to do is change the speed[0] to a negative number:
if ufo_rect.left < 0: speed[0] = -speed[0]

If the right edge of the ufo goes off right edge, reverse x direction.

A game window has an image of a boxed u f o on the extreme right with the number 640 on top of it, and 0 on the opposite side.

Again, change the speed[0] to a negative number:
if ufo_rect.right > 640: speed[0] = -speed[0]

Do the same with the top and bottom. Give it a try.

Let’s take a look at the program . Open anim03.py. Here, you’ll see the ufo bounce around the screen.

A window has a code for bouncing u f o around the screen. The line, if u f o goes off right edge reverse x direction, is boxed.

When the ufo moves toward the right wall, x (speed[0]) is increasing and y (speed[1]) is increasing.

A game window has an image of u f o on the upper right with an oblique arrow, a rightward arrow labeled positive x, and a downward arrow, positive y.

When the ufo hits the right wall, we change the direction of x (speed[0]), but not y (speed[1]).

A game window has an image of u f o on the upper right with an oblique arrow, a leftward arrow labeled negative x, and a downward arrow, positive y.

Now x (speed[0]) is decreasing, but y (speed[1]) is still increasing. Similarly for the other three sides.

What happens if you change the speed[ ] variables?
speed = [??, ??]

How would we add another ufo?

How would we add our rocket ship from the previous section?

To animate a character, you need to load your frames into a list:
frames = [pygame.image.load('frame1.png'),
          pygame.image.load('frame2.png'),
          pygame.image.load('frame3.png')]
Now, inside your main game loop, you can draw the frame using the .blit() method to draw the frame from the frames list:
gamewindow.blit(frames[counter], (x,y))
Select next frame in list, and loop back to first frame at the end of the list. We can do this with the len() function to return the number of frames in the list and modulus division.
counter = (counter + 1) % len(frames)

Let’s take a look at the program . Open spriteanim.py.

A window has a code for animating a character. The lines, load animation frames into a list, redraw sprite in a new position, and move to next frame in frames list, are boxed.

With this particular animation, we have three frames to animate the flame effect on the rocket.

A game window has an image of a rocket on the upper left.

Summary

In this chapter, you learned that
  • Pygame is a library of Python modules designed for writing computer games. Pygame adds functionality to create fully featured games and multimedia applications using the Python language.

  • The game loop is used to draw our sprites, update the screen, and keep the program running.

  • The event loop checks for events such as a keypress.

  • The refresh rate is how fast the screen is redrawn.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.130.19