Wednesday, 16 January 2013

The Game Application Code


The Game Application Code

The actual game code is divided into three parts that should be combined
to make the final game. In the following discussion, we go through the
listings one by one.

Example 37: UFO Zapper (1/3)

import key_codes, appuifw, e32, graphics, random
MAX_UFO_SIZE = 50
MAX_UFOS = 7
UFO_TIME = 100.0
PAD_W = 40

PAD_H = 15
PAD_COLOR = (12, 116, 204)
PAD_SPEED = 7
LASER_COLOR = (255, 0, 204)
TIME = 1000
def handle_redraw(rect):
global shoot, sleep, ufos, timer
buf.clear((0, 0, 0))
buf.rectangle((pad_x, H - PAD_H, pad_x + PAD_W, H), fill = PAD_COLOR)
if shoot:
x = pad_x + PAD_W / 2
buf.line((x, H - PAD_H, x, 0), width = 2, outline = LASER_COLOR)
shoot = False
sleep = 0.1
check_hits(x)
else:
sleep = 0.01
for x, y, s, t, hit in ufos:
f = 1.0 - (timer - t) / UFO_TIME
if hit:
c = (255, 0, 0)
else:
c = (0, f * 255, 0)
buf.ellipse((x, y, x + s, y + s), fill = c)
buf.text((10, 40), u"%d" % score, fill = LASER_COLOR, font = "title")
buf.text((W - 70, 40), u"%d" % (TIME - timer),
fill = LASER_COLOR, font = "title")
canvas.blit(buf)


The first part of the game code in Example 37 declares the constants
needed in the game:
• MAX UFO SIZE gives the maximum size of a UFO in pixels.
• MAX UFOS controls how many UFOs are shown at once on the
screen.
• UFO TIME controls for how long a UFO stays on screen.
• PAD W and PAD H determine the pad size in pixels.
• PAD COLOR determines color of the pad.
• PAD SPEED determines how many pixels the pad advances in one
frame.
• LASER COLOR is the color of the laser beam.
• TIME specifies for how many frames the game is played. This is
approximately TIME * 0.05 seconds.


The function handle redraw() is responsible for drawing the game
on screen based on the internal state of the game. First, the previous
frame is cleared and the pad is drawn to its current location on the X axis.
If the player has activated the laser beam with the Select key, the beam is
drawn and the function check hits() is called to determine whether
any UFOs have been hit. Then the laser beam is switched off again
with shoot = False and the length of the pause (sleep) is temporarily
increased to a tenth of a second so the beam and possible hits can be
seen easily.
After this, the UFOs are drawn based on the list ufos, which contains
the coordinates, size and lifetime of each UFO. The shade of a UFO is
determined according to its age: the closer the age is to its maximum
lifetime UFO TIME, the darker shade of green is selected. However, if the
UFO has been hit, as determined by the check hits function above,
it is painted in glowing red. Finally, the current score and time are drawn
on screen.








No comments:

Post a Comment