PYTHON
Create a 2D shooter
Putting the shooter into top-down shooter, Calvin Robinson brings us another game programming tutorial: Reservoir Bunnies.
Calvin Robinson
OUR EXPERT
Calvin Robinson is a former Assistant Principal and Computer Science teacher with a degree in Computer Games Design and Programming BSc (Hons). Twitter.com/CalvinRobinson.
QUICK TIP
The next logical step would be to replace our resources with your own custom creations. A good place to begin would be altering the colours of our images in Gimp.
We’re going to have a go at creating our own 2D shooter. We’ll be using Python for this tutorial, so make sure it’s installed and updated, along with the PyGame module. pip3 install pygame should get everything set up. We’ll need some image and sound resource files which can be downloaded from the LXF archives website, along with a complete copy of the source code for reference.
Launch Python IDLE and select File > New File to create a new document in the Script window. It’s important to type code in the Script window, rather than Shell, because it’s then editable and saveable.
We’re going to start off by importing PyGame, since this module provides a lot of game mechanics that we’ll want to tap into. We’ll also initialise our game world ( init ) and set the screen resolution:
import pygame
from pygame.locals import *
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
Now that we have a working game environment, we’ll need to start adding things to it. Let’s begin with our player character. Loading in image sprites is one area PyGame comes in very handy:
player = pygame.image.load("resources/images/dude. png")
Iteration in Python enables us to essentially loop parts of our code. We have two methods of doing this, with either a counting loop or a conditional loop. Let’s set up a conditional loop to keep running through our game code. Our first loop will take care of a few things: firstly, clearing the screen before we do anything else; then we’ll draw screen elements - that is, our player character (starting at x, y coordinates 100,100); next we’ll update the screen; finally we’ll implement an additional conditional loop to check if the player has clicked the ‘X’ to close the game window, and if so, we’ll close everything down accordingly:
while 1:
screen.fill(0)
screen.blit(player, (100,100))
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
Pygame.quit() shouldn’t be necessary these days, as the interpreter should automatically call it while being shut down; however it’s best practice to include this to prevent the game from hanging.