Converting a Basic Game to Python - Part II
In this second post, we’re going to improve our game.
Although the new version runs in Python, it still looks like an old 80s game. The first thing to fix is the animation. Since we’re using a 280 by 192 point coordinate system to simulate Apple coordinates, we multiply each coordinate by 4 when drawing. To make it look similar to the original Apple, I reduced the number of frames to 8 per second. That’s why the animation looks so jerky! To get it running at 60 frames, we need to multiply the velocities by the ratio between the old and new frame numbers: 8/60. The new version defines some constants for this:
FRAMES_ORIGINAL = 8
FRAMES_NEW = 60
RATIO = FRAMES_ORIGINAL / FRAMES_NEW
Looking at the code, it’s easy to see that the bullet, plane, and bases are objects. Let’s extract the game logic and divide operations into update and draw. In this case, update calculates the new object position, while draw performs the actual drawing.
class Plane:
def __init__(self, game, color=3):
self.color = color
self.plane_velocity = (random.randint(0, 6) + 4) * RATIO
self.plane_altitude = 159 - (random.randint(0, 135) + 11)
self.plane_position = self.plane_velocity
self.active = True
self.game = game
def draw(self):
y = self.plane_altitude
x = self.plane_position
set_color(self.color)
pyglet.graphics.draw(6, pyglet.gl.GL_LINE_LOOP,
('v2f', (x, y,
x, y - 8,
x + 3, y - 2,
x + 12, y - 2,
x + 14, y,
x, y)))
def deactivate(self):
self.active = False
self.game.deactivate(self)
def update(self):
self.plane_position += self.plane_velocity
if self.plane_position > 265:
self.deactivate()
The complete code can be seen here:
Try to understand how drawing in stages, separating the drawing from updating, allows us to display a message with an image of the game background instead of a black screen.
The next steps are:
- Clean up classes
- Multiple planes
- Multiple bullets.
- Generalize game objects into a super class.
- Display a score
- Assign keys for firing and playing again or exiting