PYGAME EXAMPLE

Pie Game

<pre>
import math
import pygame
import sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600, 500))

pygame.display.set_caption("The Pie Game")

my_font = pygame.font.Font(None, 60)

color = 200, 80, 60
width = 4
x = 300
y = 250
radius = 200
position = x - radius, y - radius, radius * 2, radius * 2

piece1 = False
piece2 = False
piece3 = False
piece4 = False

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYUP:
if event.key == pygame.K_ESCAPE:
sys.exit()
elif event.key == pygame.K_1:
piece1 = True
elif event.key == pygame.K_2:
piece2 = True
elif event.key == pygame.K_3:
piece3 = True
elif event.key == pygame.K_4:
piece4 = True

screen.fill((0, 0, 200))

# draw four numbers
textImg1 = my_font.render("1", True, color)
screen.blit(textImg1, (x + radius / 2, y - radius / 2))
textImg2 = my_font.render("2", True, color)
screen.blit(textImg2, (x - radius / 2, y - radius / 2))
textImg3 = my_font.render("3", True, color)
screen.blit(textImg3, (x - radius / 2, y + radius / 2))
textImg4 = my_font.render("4", True, color)
screen.blit(textImg4, (x + radius / 2, y + radius / 2))

if piece1:
    start_angle = math.radians(0)
    end_angle = math.radians(90)
    pygame.draw.arc(screen, color, position, start_angle,end_angle, width)
    pygame.draw.line(screen, color, (x, y), (x, y - radius), width)
    pygame.draw.line(screen, color, (x, y), (x + radius, y), width)
if piece2:
    start_angle = math.radians(90)
    end_angle = math.radians(180)
    pygame.draw.arc(screen, color, position, start_angle,end_angle, width)
    pygame.draw.line(screen, color, (x, y), (x, y - radius), width)
    pygame.draw.line(screen, color, (x, y), (x - radius, y), width)
if piece3:
    start_angle = math.radians(180)
    end_angle = math.radians(270)
    pygame.draw.arc(screen, color, position, start_angle,end_angle, width)
    pygame.draw.line(screen, color, (x, y), (x, y + radius), width)
    pygame.draw.line(screen, color, (x, y), (x - radius, y), width)
if piece4:
    start_angle = math.radians(270)
    end_angle = math.radians(360)
    pygame.draw.arc(screen, color, position, start_angle,end_angle, width)
    pygame.draw.line(screen, color, (x, y), (x, y + radius), width)
    pygame.draw.line(screen, color, (x, y), (x + radius, y), width)

if piece1 and piece2 and piece3 and piece4:
    color = 0, 255, 255


pygame.display.update()

</pre>

Palette:

<pre>import pygame
import sys
from pygame.locals import *

initialization

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

def create_scales(height):
red_scale_surface = pygame.surface.Surface((640, height))
green_scale_surface = pygame.surface.Surface((640, height))
blue_scale_surface = pygame.surface.Surface((640, height))
for x in range(640):
c = int((x / 640) * 255)
red = (c, 0, 0)
green = (0, c, 0)
blue = (0, 0, c)
line_rect = Rect(x, 0, 1, height)
pygame.draw.rect(red_scale_surface, red, line_rect)
pygame.draw.rect(green_scale_surface, green, line_rect)
pygame.draw.rect(blue_scale_surface, blue, line_rect)
return red_scale_surface, green_scale_surface, blue_scale_surface

red_scale, green_scale, blue_scale = create_scales(80)

put the color index in the middle

color = [127, 127, 127]

while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.fill((0, 0, 0))
screen.blit(red_scale, (0, 00))
screen.blit(green_scale, (0, 80))
screen.blit(blue_scale, (0, 160))
x, y = pygame.mouse.get_pos()

# 0: press left button 1:wheel button 2: right button
if pygame.mouse.get_pressed()[0]:
    for component in range(3):
        if y > component \* 80 and y < (component + 1) \* 80:
            color[component] = int((x / 639) \* 255)
    pygame.display.set_caption("PyGame Color Test - " + str(tuple(color)))

for component in range(3):
    pos = (int((color[component] / 255) \* 639), component \* 80 + 40)
    pygame.draw.circle(screen, (255, 255, 255), pos, 20)
pygame.draw.rect(screen, tuple(color), (0, 240, 640, 240))
pygame.display.update()

</pre>

Trivia:

<pre>

The Trivia Game

import sys, pygame
from pygame.locals import *

class Trivia(object):
def init(self, filename):
self.data = [] # store the question and answer
self.current = 0 # current question
self.total = 0 # total question
self.correct = 0 # correct answer you select
self.score = 0 # total score
self.scored = False # is right answer or not
self.failed = False # fail or not
self.wronganswer = 0 # wrong answer you select
self.colors = [white, white, white, white] # the color of the option

    # read trivia data from file
    f = open(filename, "r")
    trivia_data = f.readlines()
    f.close()

    # count and clean up trivia data
    for text_line in trivia_data:
        self.data.append(text_line.strip())
        self.total += 1

# show the question
def show_question(self):
    print_text(font1, 210, 5, "TRIVIA GAME")
    print_text(font2, 190, 500 - 20, "Press Keys (1-4) To Answer", purple)
    print_text(font2, 530, 5, "SCORE", purple)
    print_text(font2, 550, 25, str(self.score), purple)

    # get correct answer out of data (first)
    self.correct = int(self.data[self.current + 5])

    # display question
    question = self.current // 6 + 1
    print_text(font1, 5, 80, "QUESTION " + str(question))
    print_text(font2, 20, 120, self.data[self.current], yellow)

    # respond to correct answer
    if self.scored:
        self.colors = [white, white, white, white]
        self.colors[self.correct - 1] = green
        print_text(font1, 230, 380, "CORRECT!", green)
        print_text(font2, 170, 420, "Press Enter For Next Question", green)
    elif self.failed:
        self.colors = [white, white, white, white]
        self.colors[self.wronganswer - 1] = red
        self.colors[self.correct - 1] = green
        print_text(font1, 220, 380, "INCORRECT!", red)
        print_text(font2, 170, 420, "Press Enter For Next Question", red)

    # display answers
    print_text(font1, 5, 170, "ANSWERS")
    print_text(font2, 20, 210, "1 - " + self.data[self.current + 1], self.colors[0])
    print_text(font2, 20, 240, "2 - " + self.data[self.current + 2], self.colors[1])
    print_text(font2, 20, 270, "3 - " + self.data[self.current + 3], self.colors[2])
    print_text(font2, 20, 300, "4 - " + self.data[self.current + 4], self.colors[3])

def handle_input(self, number):
    if not self.scored and not self.failed:
        if number == self.correct:
            self.scored = True
            self.score += 1
        else:
            self.failed = True
            self.wronganswer = number

def next_question(self):
    if self.scored or self.failed:
        self.scored = False
        self.failed = False
        self.correct = 0
        self.colors = [white, white, white, white]
        self.current += 6
        if self.current >= self.total:
            self.current = 0

def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
if shadow:
imgText = font.render(text, True, (0, 0, 0))
screen.blit(imgText, (x - 2, y - 2))
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

main program begins

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("The Trivia Game")
font1 = pygame.font.Font(None, 40)
font2 = pygame.font.Font(None, 24)
white = 255, 255, 255
cyan = 0, 255, 255
yellow = 255, 255, 0
purple = 255, 0, 255
green = 0, 255, 0
red = 255, 0, 0

load the trivia data file

trivia = Trivia("trivia_data.txt")

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYUP:
if event.key == pygame.K_ESCAPE:
sys.exit()
elif event.key == pygame.K_1:
trivia.handle_input(1)
elif event.key == pygame.K_2:
trivia.handle_input(2)
elif event.key == pygame.K_3:
trivia.handle_input(3)
elif event.key == pygame.K_4:
trivia.handle_input(4)
elif event.key == pygame.K_RETURN:
trivia.next_question()

# clear the screen
screen.fill((0, 0, 200))

# display trivia data
trivia.show_question()

# update the display
pygame.display.update()

</pre>

<pre>
trivia_data.txt

What is the name of the 4th planet from the Sun?
Saturn
Mars
Earth
Venus
2
Which planet has the most moons in the solar system?
Uranus
Saturn
Neptune
Jupiter
4
Approximately how large is the Sun's diameter (width)?
65 thousand miles
45 million miles
1 million miles
825 thousand miles
3
How far is the Earth from the Sun in its orbit (on average)?
13 million miles
93 million miles
250 thousand miles
800 thousand miles
2
What causes the Earth's oceans to have tides?
The Moon
The Sun
Earth's molten core
Oxygen
1
</pre>

Mouse Demo:

<pre>

Mouse Demo

Chapter 4

import sys, pygame
from pygame.locals import *

def print_text(font, x, y, text, color=(255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

main program begins

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Mouse Demo")
font1 = pygame.font.Font(None, 24)
white = 255, 255, 255

seconds = 10
score = 0
clock_start = 0
game_over = True
mouse_x = mouse_y = 0
move_x = move_y = 0
mouse_down = mouse_up = 0
mouse_down_x = mouse_down_y = 0
mouse_up_x = mouse_up_y = 0

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, move_y = event.rel
elif event.type == MOUSEBUTTONDOWN:
mouse_down = event.button
mouse_down_x, mouse_down_y = event.pos
elif event.type == MOUSEBUTTONUP:
mouse_up = event.button
mouse_up_x, mouse_up_y = event.pos

keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
    sys.exit()

screen.fill((0, 100, 0))

print_text(font1, 0, 0, "Mouse Events")
print_text(font1, 0, 20, "Mouse position: " + str(mouse_x) +
           "," + str(mouse_y))
print_text(font1, 0, 40, "Mouse relative: " + str(move_x) +
           "," + str(move_y))

print_text(font1, 0, 60, "Mouse button down: " + str(mouse_down) +
           " at " + str(mouse_down_x) + "," + str(mouse_down_y))

print_text(font1, 0, 80, "Mouse button up: " + str(mouse_up) +
           " at " + str(mouse_up_x) + "," + str(mouse_up_y))

print_text(font1, 0, 160, "Mouse Polling")

x, y = pygame.mouse.get_pos()
print_text(font1, 0, 180, "Mouse position: " + str(x) + "," + str(y))

b1, b2, b3 = pygame.mouse.get_pressed()
print_text(font1, 0, 200, "Mouse buttons: " +
           str(b1) + "," + str(b2) + "," + str(b3))

pygame.display.update()

</pre>

Keyboard Demo:

<pre>
import sys, random, time, pygame
from pygame.locals import *

def print_text(font, x, y, text, color = (255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Keyboard Demo")
font1 = pygame.font.Font(None, 24)
font2 = pygame.font.Font(None, 200)
white = 255, 255, 255
yellow = 255, 255, 0

key_flag = False
correct_answer = 97
seconds = 10
score = 0
clock_start = 0
game_over = True
speed = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
key_flag = True
elif event.type == KEYUP:
key_flag = False

keys = pygame.key.get_pressed()


if keys[K_ESCAPE]:
    sys.exit()
if keys[K_RETURN]:
    if game_over:
        game_over = False
        score = 0
        seconds = 11
        clock_start = time.clock()

screen.fill((0, 100, 0))

if not game_over:
    current = time.clock() - clock_start
    print_text(font1, 0, 80, "Time: " + str(int(seconds - current)))

    if keys[correct_answer]:
        score += 1
        correct_answer = random.randint(97, 122)
        speed = score \* 6

    if seconds - current < 0:
        game_over = True
else:
    print_text(font1, 0, 160, "Press Enter to start")

print_text(font1, 0, 0, "Let's see how fast you can type")
print_text(font1, 0, 20, "Try to keep up for 10 seconds...")

if key_flag:
    print_text(font1, 500, 0, "<key>")

print_text(font1, 0, 100, "Speed: " + str(speed) + " letters/min")

print_text(font2, 0, 240, chr(correct_answer - 32), yellow)

pygame.display.update()

</pre>

Bomb Catcher:

<pre>

Bomb Catcher Game

Chapter 4

import sys, random, time, pygame
from pygame.locals import *

def print_text(font, x, y, text, color=(255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

main program begins

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Bomb Catching Game")
font1 = pygame.font.Font(None, 24)
pygame.mouse.set_visible(False)
white = 255, 255, 255
red = 220, 50, 50
yellow = 230, 230, 50
black = 0, 0, 0

lives = 3
score = 0
clock_start = 0
game_over = True
mouse_x = mouse_y = 0

pos_x = 300
pos_y = 460

bomb_x = random.randint(0, 500)
bomb_y = -50
vel_y = 15

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, move_y = event.rel
elif event.type == MOUSEBUTTONUP:
if game_over:
game_over = False
lives = 3
score = 0

keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
    sys.exit()

screen.fill((0, 0, 100))

if game_over:
    print_text(font1, 100, 200, "<CLICK TO PLAY>")
else:
    # move the bomb
    bomb_y += vel_y

    # has the player missed the bomb?
    if bomb_y > 500:
        # reset
        bomb_x = random.randint(0, 500)
        bomb_y = -50
        lives -= 1
        if lives == 0:
            game_over = True

    # see if player has caught the bomb
    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 10
            bomb_x = random.randint(0, 500)
            bomb_y = -50

    # draw the bomb
    pygame.draw.circle(screen, black, (bomb_x - 4, int(bomb_y) - 4), 30, 0)
    pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)

    # set basket position
    pos_x = mouse_x
    if pos_x < 0:
        pos_x = 0
    elif pos_x > 500:
        pos_x = 500
    # draw basket
    pygame.draw.rect(screen, black, (pos_x - 4, pos_y - 4, 120, 40), 0)
    pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

# print # of lives
print_text(font1, 0, 0, "LIVES: " + str(lives))

# print score
print_text(font1, 500, 0, "SCORE: " + str(score))

pygame.display.update()

</pre>

Circle Demo:

<pre>

Circle Demo

Chapter 5

import random, math, pygame
from pygame.locals import *

main program begins

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Circle Demo")
screen.fill((0, 0, 100))

pos_x = 300
pos_y = 250
radius = 200
angle = 360

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
sys.exit()

# increment angle
angle += 1
if angle >= 360:
    angle = 0
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    color = r, g, b

# calculate coordinates
x = math.cos(math.radians(angle)) \* radius
y = math.sin(math.radians(angle)) \* radius

# draw one step around the circle
pos = (int(pos_x + x), int(pos_y + y))
pygame.draw.circle(screen, color, pos, 1, 0)

pygame.display.update()

</pre>

Clock:

<pre>

Analog Clock Demo

Chapter 5

import sys, random, math, pygame
from pygame.locals import *
from datetime import datetime, date, time

def print_text(font, x, y, text, color=(255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

def wrap_angle(angle):
return angle % 360

main program begins

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Analog Clock Demo")
font = pygame.font.Font(None, 36)
orange = 220, 180, 0
white = 255, 255, 255
yellow = 255, 255, 0
pink = 255, 100, 100

pos_x = 300
pos_y = 250
radius = 250
angle = 360

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
sys.exit()

screen.fill((0, 0, 100))

# draw one step around the circle
pygame.draw.circle(screen, white, (pos_x, pos_y), radius, 6)

# draw the clock numbers 1-12
for n in range(1, 13):
    angle = math.radians(n \* (360 / 12) - 90)
    x = math.cos(angle) \* (radius - 20) - 10
    y = math.sin(angle) \* (radius - 20) - 10
    print_text(font, pos_x + x, pos_y + y, str(n))

# get the time of day
today = datetime.today()
hours = today.hour % 12
minutes = today.minute
seconds = today.second

# draw the hours hand
hour_angle = wrap_angle(hours \* (360 / 12) - 90 + 30 \* minutes / 60)
hour_angle = math.radians(hour_angle)
hour_x = math.cos(hour_angle) \* (radius - 80)
hour_y = math.sin(hour_angle) \* (radius - 80)
target = (pos_x + hour_x, pos_y + hour_y)
pygame.draw.line(screen, pink, (pos_x, pos_y), target, 25)

# draw the minutes hand
min_angle = wrap_angle(minutes \* (360 / 60) - 90)
min_angle = math.radians(min_angle)
min_x = math.cos(min_angle) \* (radius - 60)
min_y = math.sin(min_angle) \* (radius - 60)
target = (pos_x + min_x, pos_y + min_y)
pygame.draw.line(screen, orange, (pos_x, pos_y), target, 12)

# draw the seconds hand
sec_angle = wrap_angle(seconds \* (360 / 60) - 90)
sec_angle = math.radians(sec_angle)
sec_x = math.cos(sec_angle) \* (radius - 40)
sec_y = math.sin(sec_angle) \* (radius - 40)
target = (pos_x + sec_x, pos_y + sec_y)
pygame.draw.line(screen, yellow, (pos_x, pos_y), target, 6)

# cover the center
pygame.draw.circle(screen, white, (pos_x, pos_y), 20)

print_text(font, 0, 0, str(hours) + ":" + str(minutes) + ":" + str(seconds))

pygame.display.update()

</pre>

OrbitDemo:

<pre>

Orbit Demo

Chapter 5

import sys, random, math, pygame
from pygame.locals import *

Point class

class Point(object):
def init(self, x, y):
self.__x = x
self.__y = y

# X property
def getx(self): return self.__x

def setx(self, x): self.__x = x

x = property(getx, setx)

# Y property
def gety(self): return self.__y

def sety(self, y): self.__y = y

y = property(gety, sety)

def __str__(self):
    return "{X:" + "{:.0f}".format(self.__x) + \
           ",Y:" + "{:.0f}".format(self.__y) + "}"

print_text function

def print_text(font, x, y, text, color=(255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

wrap_angle function

def wrap_angle(angle):
return angle % 360

main program begins

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Orbit Demo")
font = pygame.font.Font(None, 18)

load bitmaps

space = pygame.image.load("space.png").convert_alpha()
planet = pygame.image.load("planet2.png").convert_alpha()
ship = pygame.image.load("freelance.png").convert_alpha()
width, height = ship.get_size()
ship = pygame.transform.smoothscale(ship, (width // 2, height // 2))

radius = 250
angle = 0.0
pos = Point(0, 0)
old_pos = Point(0, 0)

repeating loop

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
sys.exit()

# draw background
screen.blit(space, (0, 0))

# draw planet
width, height = planet.get_size()
screen.blit(planet, (400 - width / 2, 300 - height / 2))

# move the ship
angle = wrap_angle(angle - 1)
pos.x = math.sin(math.radians(angle)) \* radius
pos.y = math.cos(math.radians(angle)) \* radius

# rotate the ship

scratch_ship = pygame.transform.rotate(ship, angle)
# draw the ship
width, height = scratch_ship.get_size()
x = 400 + pos.x - width // 2
y = 300 + pos.y - height // 2
screen.blit(scratch_ship, (x, y))

print_text(font, 0, 0, "Orbit: " + "{:.0f}".format(angle))
print_text(font, 0, 20, "Rotation: " + "{:.2f}".format(rangle))
print_text(font, 0, 40, "Position: " + str(pos))
print_text(font, 0, 60, "Old Pos: " + str(old_pos))

pygame.display.update()

# remember position
old_pos.x = pos.x
old_pos.y = pos.y

</pre>

Escape the dragon:

<pre>

Escape The Dragon Game

Chapter 7

import sys, time, random, math, pygame
from pygame.locals import *

class MySprite(pygame.sprite.Sprite):
def init(self, target):
pygame.sprite.Sprite.init(self) # extend the base Sprite class
self.master_image = None
self.frame = 0
self.old_frame = -1
self.frame_width = 1
self.frame_height = 1
self.first_frame = 0
self.last_frame = 0
self.columns = 1
self.last_time = 0

# X property
def _getx(self):
    return self.rect.x

def _setx(self, value):
    self.rect.x = value

X = property(_getx, _setx)

# Y property
def _gety(self):
    return self.rect.y

def _sety(self, value):
    self.rect.y = value

Y = property(_gety, _sety)

# position property
def _getpos(self):
    return self.rect.topleft

def _setpos(self, pos):
    self.rect.topleft = pos

position = property(_getpos, _setpos)

def load(self, filename, width, height, columns):
    self.master_image = pygame.image.load(filename).convert_alpha()
    self.frame_width = width
    self.frame_height = height
    self.rect = Rect(0, 0, width, height)
    self.columns = columns
    # try to auto-calculate total frames
    rect = self.master_image.get_rect()
    self.last_frame = (rect.width // width) \* (rect.height // height) - 1

def update(self, current_time, rate=30):
    # update animation frame number
    if current_time > self.last_time + rate:
        self.frame += 1
        if self.frame > self.last_frame:
            self.frame = self.first_frame
        self.last_time = current_time

    # build current frame only if it changed
    if self.frame != self.old_frame:
        frame_x = (self.frame % self.columns) \* self.frame_width
        frame_y = (self.frame // self.columns) \* self.frame_height
        rect = Rect(frame_x, frame_y, self.frame_width, self.frame_height)
        self.image = self.master_image.subsurface(rect)
        self.old_frame = self.frame

def __str__(self):
    return str(self.frame) + "," + str(self.first_frame) + \
           "," + str(self.last_frame) + "," + str(self.frame_width) + \
           "," + str(self.frame_height) + "," + str(self.columns) + \
           "," + str(self.rect)

def print_text(font, x, y, text, color=(255, 255, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))

def reset_arrow():
y = random.randint(250, 350)
arrow.position = 800, y

main program begins

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Escape The Dragon Game")
font = pygame.font.Font(None, 18)
framerate = pygame.time.Clock()

load bitmaps

bg = pygame.image.load("background.png").convert_alpha()

create a sprite group

group = pygame.sprite.Group()

create the dragon sprite

dragon = MySprite(screen)
dragon.load("dragon.png", 260, 150, 3)
dragon.position = 100, 230
group.add(dragon)

create the player sprite

player = MySprite(screen)
player.load("caveman.png", 50, 64, 8)
player.first_frame = 1
player.last_frame = 7
player.position = 400, 303
group.add(player)

create the arrow sprite

arrow = MySprite(screen)
arrow.load("flame.png", 40, 16, 1)
arrow.position = 800, 320
group.add(arrow)

arrow_vel = 8.0
game_over = False
you_win = False
player_jumping = False
jump_vel = 0.0
player_start_y = player.Y
lives = 3
score = 0
font1 = pygame.font.Font(None, 24)
start_time = 0

repeating loop

while True:
framerate.tick(30)
# total time
ticks = pygame.time.get_ticks()

for event in pygame.event.get():
    if event.type == QUIT: sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
    sys.exit()
elif keys[K_SPACE]:
    if not player_jumping:
        player_jumping = True
        jump_vel = -11.0

# update the arrow
if not game_over:
    arrow.X -= arrow_vel
    if arrow.X < -40: reset_arrow()

    # did arrow hit player?
    if pygame.sprite.collide_rect(arrow, player):
        reset_arrow()
        player.X -= 10

    # did arrow hit dragon?
    if pygame.sprite.collide_rect(arrow, dragon):
        reset_arrow()
        dragon.X -= 10

    # did dragon eat the player?
    if pygame.sprite.collide_rect(player, dragon):
        game_over = True

    # did the dragon get defeated?
    if dragon.X < -100:
        you_win = True
        game_over = True

        # is the player jumping?
    if player_jumping:
        player.Y += jump_vel
        jump_vel += 0.5
        if player.Y > player_start_y:
            player_jumping = False
            player.Y = player_start_y
            jump_vel = 0.0

# draw the background
screen.blit(bg, (0, 0))

# update sprites
if not game_over:
    group.update(ticks, 50)
    score += 1

# draw sprites
group.draw(screen)

print_text(font, 350, 560, "Press SPACE to jump!")

if game_over:
    print_text(font, 360, 100, "G A M E   O V E R")
    if you_win:
        print_text(font, 330, 130, "YOU BEAT THE DRAGON!")
    else:
        print_text(font, 330, 130, "THE DRAGON GOT YOU!")

        # print # of lives
print_text(font1, 0, 0, "LIVES: " + str(lives))

# print score
print_text(font1, 500, 0, "SCORE: " + str(score))

pygame.display.update()

</pre>

Zombie Mob:

<pre>

Zombie Mob Game

Chapter 8

import itertools, sys, time, random, math, pygame
from pygame.locals import *
from MyLibrary import *

def calc_velocity(direction, vel=1.0):
velocity = Point(0,0)
if direction == 0: #north
velocity.y = -vel
elif direction == 2: #east
velocity.x = vel
elif direction == 4: #south
velocity.y = vel
elif direction == 6: #west
velocity.x = -vel
return velocity

def reverse_direction(sprite):
if sprite.direction == 0:
sprite.direction = 4
elif sprite.direction == 2:
sprite.direction = 6
elif sprite.direction == 4:
sprite.direction = 0
elif sprite.direction == 6:
sprite.direction = 2

main program begins

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Collision Demo")
font = pygame.font.Font(None, 36)
timer = pygame.time.Clock()

create sprite groups

player_group = pygame.sprite.Group()
zombie_group = pygame.sprite.Group()
health_group = pygame.sprite.Group()

create the player sprite

player = MySprite()
player.load("farmer walk.png", 96, 96, 8)
player.position = 80, 80
player.direction = 4
player_group.add(player)

create the zombie sprite

zombie_image = pygame.image.load("zombie walk.png").convert_alpha()
for n in range(0, 10):
zombie = MySprite()
zombie.load("zombie walk.png", 96, 96, 8)
zombie.position = random.randint(0, 700), random.randint(0, 500)
zombie.direction = random.randint(0, 3) * 2
zombie_group.add(zombie)

create heath sprite

health = MySprite()
health.load("health.png", 32, 32, 1)
health.position = 400, 300
health_group.add(health)

game_over = False
player_moving = False
player_health = 100

start_time = 0

repeating loop

while True:
timer.tick(30)
ticks = pygame.time.get_ticks()

# add zombie every 10 seconds
if ticks - start_time > 10000:
    zombie = MySprite()
    zombie.load("zombie walk.png", 96, 96, 8)
    zombie.position = random.randint(0, 700), random.randint(0, 500)
    zombie.direction = random.randint(0, 3) \* 2
    zombie_group.add(zombie)
    start_time = ticks

for event in pygame.event.get():
    if event.type == QUIT: sys.exit()
keys = pygame.key.get_pressed()

if keys[K_ESCAPE]: sys.exit()
elif keys[K_UP] or keys[K_w]:
    player.direction = 0
    player_moving = True
elif keys[K_RIGHT] or keys[K_d]:
    player.direction = 2
    player_moving = True
elif keys[K_DOWN] or keys[K_s]:
    player.direction = 4
    player_moving = True
elif keys[K_LEFT] or keys[K_a]:
    player.direction = 6
    player_moving = True
else:
    player_moving = False

if not game_over:
    # set animation frames based on player's direction
    player.first_frame = player.direction \* player.columns
    player.last_frame = player.first_frame + player.columns-1
    if player.frame < player.first_frame:
        player.frame = player.first_frame

    if not player_moving:
        #stop animating when player is not pressing a key
        player.frame = player.first_frame = player.last_frame
    else:
        #move player in direction 
        player.velocity = calc_velocity(player.direction, 1.5)
        player.velocity.x \*= 1.5
        player.velocity.y \*= 1.5

    #update player sprite
    player_group.update(ticks, 50)

    #manually move the player
    if player_moving:
        player.X += player.velocity.x
        player.Y += player.velocity.y
        if player.X < 0: player.X = 0
        elif player.X > 700: player.X = 700
        if player.Y < 0: player.Y = 0
        elif player.Y > 500: player.Y = 500

    #update zombie sprites
    zombie_group.update(ticks, 50)

    #manually iterate through all the zombies
    for z in zombie_group:
        #set the zombie's animation range
        z.first_frame = z.direction \* z.columns
        z.last_frame = z.first_frame + z.columns-1
        if z.frame < z.first_frame:
            z.frame = z.first_frame
        z.velocity = calc_velocity(z.direction)

        #keep the zombie on the screen        
        z.X += z.velocity.x
        z.Y += z.velocity.y
        if z.X < 0 or z.X > 700 or z.Y < 0 or z.Y > 500:
            reverse_direction(z)
        

    #check for collision with zombies
    attacker = None
    attacker = pygame.sprite.spritecollideany(player, zombie_group)
    if attacker != None:
        #we got a hit, now do a more precise check
        if pygame.sprite.collide_rect_ratio(0.5)(player,attacker):
            player_health -= 10
            if attacker.X < player.X:   attacker.X -= 10
            elif attacker.X > player.X: attacker.X += 10
        else:
            attacker = None

    #update the health drop
    health_group.update(ticks, 50)

    #check for collision with health
    if pygame.sprite.collide_rect_ratio(0.5)(player,health):
        player_health += 30
        if player_health > 100: player_health = 100
        health.X = random.randint(0,700)
        health.Y = random.randint(0,500)
    

#is player dead?
if player_health <= 0:
    game_over = True


#clear the screen
screen.fill((50,50,100))

#draw sprites
health_group.draw(screen)
zombie_group.draw(screen)
player_group.draw(screen)

#draw energy bar
pygame.draw.rect(screen, (50,150,50,180), Rect(300,570,player_health \* 2,25))
pygame.draw.rect(screen, (100,200,100,180), Rect(300,570,200,25), 2)

if game_over:
    print_text(font, 300, 100, "G A M E   O V E R")

pygame.display.update()

</pre>

BlockBreaker:

<pre>

Block Breaker Game

Chapter 9

import sys, time, random, math, pygame
from pygame.locals import *
from MyLibrary import *

levels = (
(1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,0,0,1,1,1,1,1,
1,1,1,1,1,0,0,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1),

(2,2,2,2,2,2,2,2,2,2,2,2,
2,0,0,2,2,2,2,2,2,0,0,2,
2,0,0,2,2,2,2,2,2,0,0,2,
2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,
2,0,0,2,2,2,2,2,2,0,0,2,
2,0,0,2,2,2,2,2,2,0,0,2,
2,2,2,2,2,2,2,2,2,2,2,2),

(3,3,3,3,3,3,3,3,3,3,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,0,0,0,3,3,0,0,0,3,3,
3,3,3,3,3,3,3,3,3,3,3,3),
)

this function increments the level

def goto_next_level():
global level, levels
level += 1
if level > len(levels)-1:
level = 0
load_level()

this function updates the blocks in play

def update_blocks():
global block_group, waiting
if len(block_group) == 0: #all blocks gone?
goto_next_level()
waiting = True
block_group.update(ticks, 50)

this function sets up the blocks for the level

def load_level():
global level, block, block_image, block_group, levels

block_image = pygame.image.load("blocks.png").convert_alpha()

block_group.empty() #reset block group

for bx in range(0, 12):
    for by in range(0,10):
        block = MySprite()
        block.set_image(block_image, 58, 28, 4)
        x = 40 + bx \* (block.frame_width+1)
        y = 60 + by \* (block.frame_height+1)
        block.position = x, y

        #read blocks from level data
        num = levels[level][by \* 12+bx]
        block.first_frame = num-1
        block.last_frame = num-1
        if num > 0: #0 is blank
            block_group.add(block)

print(len(block_group))

this function initializes the game

def game_init():
global screen, font, timer
global paddle_group, block_group, ball_group
global paddle, block_image, block, ball

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Block Breaker Game")
font = pygame.font.Font(None, 36)
pygame.mouse.set_visible(False)
timer = pygame.time.Clock()

#create sprite groups
paddle_group = pygame.sprite.Group()
block_group = pygame.sprite.Group()
ball_group = pygame.sprite.Group()

#create the paddle sprite
paddle = MySprite()
paddle.load("paddle.png")
paddle.position = 400, 540
paddle_group.add(paddle)

#create ball sprite
ball = MySprite()
ball.load("ball.png")
ball.position = 400,300
ball_group.add(ball)

this function moves the paddle

def move_paddle():
global movex,movey,keys,waiting

paddle_group.update(ticks, 50)


if keys[K_LEFT]: paddle.velocity.x = -10.0
elif keys[K_RIGHT]: paddle.velocity.x = 10.0
elif movex < -2:
    paddle.velocity.x = movex
elif movex > 2:
    paddle.velocity.x = movex
else:
   paddle.velocity.x = 0

paddle.X += paddle.velocity.x
if paddle.X < 0: paddle.X = 0
elif paddle.X > 710: paddle.X = 710

this function resets the ball's velocity

def reset_ball():
ball.velocity = Point(4.5, -7.0)

this function moves the ball

def move_ball():
global waiting, ball, game_over, lives

#move the ball            
ball_group.update(ticks, 50)
if waiting:
    ball.X = paddle.X + 40
    ball.Y = paddle.Y - 20
ball.X += ball.velocity.x
ball.Y += ball.velocity.y
if ball.X < 0:
    ball.X = 0
    ball.velocity.x \*= -1
elif ball.X > 780:
    ball.X = 780
    ball.velocity.x \*= -1
if ball.Y < 0:
    ball.Y = 0
    ball.velocity.y \*= -1
elif ball.Y > 580: #missed paddle
    waiting = True
    lives -= 1
    if lives < 1: game_over = True

this function test for collision between ball and paddle

def collision_ball_paddle():
if pygame.sprite.collide_rect(ball, paddle):
ball.velocity.y = -abs(ball.velocity.y)
bx = ball.X + 8
by = ball.Y + 8
px = paddle.X + paddle.frame_width/2
py = paddle.Y + paddle.frame_height/2
if bx < px: #left side of paddle?
ball.velocity.x = -abs(ball.velocity.x)
else: #right side of paddle?
ball.velocity.x = abs(ball.velocity.x)

this function tests for collision between ball and blocks

def collision_ball_blocks():
global score, block_group, ball

hit_block = pygame.sprite.spritecollideany(ball, block_group)
if hit_block != None:
    score += 10
    block_group.remove(hit_block)
    bx = ball.X + 8
    by = ball.Y + 8

    #hit middle of block from above or below?
    if bx > hit_block.X+5 and bx < hit_block.X + hit_block.frame_width-5:
        if by < hit_block.Y + hit_block.frame_height/2: #above?
            ball.velocity.y = -abs(ball.velocity.y)
        else: #below?
            ball.velocity.y = abs(ball.velocity.y)

    #hit left side of block?
    elif bx < hit_block.X + 5:
        ball.velocity.x = -abs(ball.velocity.x)
    #hit right side of block?
    elif bx > hit_block.X + hit_block.frame_width - 5:
        ball.velocity.x = abs(ball.velocity.x)

    #handle any other situation
    else:
        ball.velocity.y \*= -1

main program begins

game_init()
game_over = False
waiting = True
score = 0
lives = 3
level = 0
load_level()

repeating loop

while True:
timer.tick(30)
ticks = pygame.time.get_ticks()

#handle events
for event in pygame.event.get():
    if event.type == QUIT: sys.exit()
    elif event.type == MOUSEMOTION:
        movex,movey = event.rel
    elif event.type == MOUSEBUTTONUP:
        if waiting:
            waiting = False
            reset_ball()
    elif event.type == KEYUP:
        if event.key == K_RETURN: goto_next_level()

#handle key presses
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]: sys.exit()


#do updates
if not game_over:

    if keys[K_SPACE]:
        if waiting:
            waiting = False
            reset_ball()
            
    update_blocks()
    move_paddle()
    move_ball()
    collision_ball_paddle()
    collision_ball_blocks()

#do drawing
screen.fill((50,50,100))
block_group.draw(screen)
ball_group.draw(screen)
paddle_group.draw(screen)
print_text(font, 0, 0, "SCORE " + str(score))
print_text(font, 200, 0, "LEVEL " + str(level+1))
print_text(font, 400, 0, "BLOCKS " + str(len(block_group)))
print_text(font, 670, 0, "BALLS " + str(lives))
if game_over:
    print_text(font, 300, 380, "G A M E   O V E R")
pygame.display.update()

</pre>

Oil Spill:

<pre>

Oil Spill Game

Chapter 10

import sys, time, random, math, pygame
from pygame.locals import *
from MyLibrary import *

darktan = 190,190,110,255
tan = 210,210,130,255

class OilSprite(MySprite):
def init(self):
MySprite.init(self)
self.radius = random.randint(0,60) + 30 #radius 30 to 90
play_sound(new_oil)

def update(self, timing, rate=30):
    MySprite.update(self, timing, rate)

def fade(self):
    r2 = self.radius//2
    color = self.image.get_at((r2,r2))
    if color.a > 5:
        color.a -= 5
        pygame.draw.circle(self.image, color, (r2, r2), r2, 0)
    else:
        oil_group.remove(self)
        play_sound(clean_oil)

this function initializes the game

def game_init():
global screen, backbuffer, font, timer, oil_group, cursor, cursor_group

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Oil Spill Game")
font = pygame.font.Font(None, 36)
pygame.mouse.set_visible(False)
timer = pygame.time.Clock()

#create a drawing surface
backbuffer = pygame.Surface((800,600))
backbuffer.fill(darktan)

#create oil list
oil_group = pygame.sprite.Group()

#create cursor sprite
cursor = MySprite()
cursor.radius = 60
image = pygame.Surface((60,60)).convert_alpha()
image.fill((255,255,255,0))
pygame.draw.circle(image, (80,80,220,70), (30,30), 30, 0)
pygame.draw.circle(image, (80,80,250,255), (30,30), 30, 4)
cursor.set_image(image)
cursor_group = pygame.sprite.GroupSingle()
cursor_group.add(cursor)

this function initializes the audio system

def audio_init():
global new_oil, clean_oil

#initialize the audio mixer
pygame.mixer.init() #not always called by pygame.init()

#load sound files
new_oil = pygame.mixer.Sound("new_oil.wav")
clean_oil = pygame.mixer.Sound("clean_oil.wav")

def play_sound(sound):
channel = pygame.mixer.find_channel(True)
channel.set_volume(0.5)
channel.play(sound)

def add_oil():
global oil_group, new_oil

oil = OilSprite()
image = pygame.Surface((oil.radius,oil.radius)).convert_alpha()
image.fill((255,255,255,0))
oil.fadelevel = random.randint(50,150)
oil_color = 10,10,20,oil.fadelevel
r2 = oil.radius//2
pygame.draw.circle(image, oil_color, (r2,r2), r2, 0)
oil.set_image(image)
oil.X = random.randint(0,760)
oil.Y = random.randint(0,560)
oil_group.add(oil)

play_sound(new_oil)

main program begins

game_init()
audio_init()
game_over = False
last_time = 0

repeating loop

while True:
timer.tick(30)
ticks = pygame.time.get_ticks()

for event in pygame.event.get():
    if event.type == QUIT: sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]: sys.exit()


#get mouse input
b1,b2,b3 = pygame.mouse.get_pressed()
mx,my = pygame.mouse.get_pos()
pos = (mx+30,my+30)
if b1 > 0:
    pygame.draw.circle(backbuffer, tan, pos, 30, 0)

#collision test
oil_hit = None
for oil in oil_group:
    if pygame.sprite.collide_circle_ratio(0.5)(cursor, oil):
        oil_hit = oil
        if b1 > 0: oil_hit.fade()
        break

#add new oil sprite once per second
if ticks > last_time + 1000:
    add_oil()
    last_time = ticks


#draw backbuffer
screen.blit(backbuffer, (0,0))

#draw oil
oil_group.update(ticks)
oil_group.draw(screen)

#draw cursor
cursor.position = (mx,my)
cursor_group.update(ticks)
cursor_group.draw(screen)

if oil_hit: print_text(font, 0, 0, "OIL SPLOTCH - CLEAN IT!")
else: print_text(font, 0, 0, "CLEAN")
pygame.display.update()

</pre>

Snake:

<pre>

Snake Game

Chapter 11

import sys, time, random, math, pygame
from pygame.locals import *
from MyLibrary import *

class Food(MySprite):
def init(self):
MySprite.init(self)
image = pygame.Surface((32,32)).convert_alpha()
image.fill((255,255,255,0))
pygame.draw.circle(image, (250,250,50), (16,16), 16, 0)
self.set_image(image)
MySprite.update(self, 0, 30) #create frame image
self.X = random.randint(0,23) * 32
self.Y = random.randint(0,17) * 32

class SnakeSegment(MySprite):
def init(self,color=(20,200,20)):
MySprite.init(self)
image = pygame.Surface((32,32)).convert_alpha()
image.fill((255,255,255,0))
pygame.draw.circle(image, color, (16,16), 16, 0)
self.set_image(image)
MySprite.update(self, 0, 30) #create frame image

class Snake():
def init(self):
self.velocity = Point(-1,0)
self.old_time = 0
head = SnakeSegment((50,250,50))
head.X = 12 * 32
head.Y = 9* 32
self.segments = list()
self.segments.append(head)
self.add_segment()
self.add_segment()

def update(self,ticks):
    global step_time #additional code
    if ticks > self.old_time + step_time: #modified code
        self.old_time = ticks
        #move body segments
        for n in range(len(self.segments)-1, 0, -1):
            self.segments[n].X = self.segments[n-1].X
            self.segments[n].Y = self.segments[n-1].Y
        #move snake head
        self.segments[0].X += self.velocity.x \* 32
        self.segments[0].Y += self.velocity.y \* 32

def draw(self,surface):
    for segment in self.segments: 
        surface.blit(segment.image, (segment.X, segment.Y))

def add_segment(self):
    last = len(self.segments)-1
    segment = SnakeSegment()
    start = Point(0,0)
    if self.velocity.x < 0: start.x = 32
    elif self.velocity.x > 0: start.x = -32
    if self.velocity.y < 0: start.y = 32
    elif self.velocity.y > 0: start.y = -32
    segment.X = self.segments[last].X + start.x
    segment.Y = self.segments[last].Y + start.y
    self.segments.append(segment)

this function gets the snake's current direction

def get_current_direction():
global head_x,head_y
first_segment_x = snake.segments[1].X//32
first_segment_y = snake.segments[1].Y//32
if head_x-1 == first_segment_x: return "right"
elif head_x+1 == first_segment_x: return "left"
elif head_y-1 == first_segment_y: return "down"
elif head_y+1 == first_segment_y: return "up"

this function gets the direction to the food

def get_food_direction():
global head_x,head_y
food = Point(0,0)
for obj in food_group:
food = Point(obj.X//32,obj.Y//32)
direction = get_current_direction()

if direction == "up" or direction == "down":
    if head_x < food.x:
        return "right"
    elif head_x > food.x:
        return "left"
    else:
        return direction

if direction == "left" or direction == "right":
    if head_y < food.y:
        return "down"
    elif head_y > food.y:
        return "up"
    else:
        return direction

this function causes snake to move automatically

def auto_move():
global head_x, head_y
direction = get_current_direction()
food_dir = get_food_direction()

print(direction + ":" + food_dir+":" + str(head_x) + ":" + str(head_y))
if direction == "up":
    if food_dir == "left":
        direction = "left"
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "up"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "right"
                break

    if food_dir == "right":
        direction = "right"
        for segment in snake.segments:
            if segment.X // 32 == head_x + 1:
                direction == "up"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "left"
                break

    if food_dir == "up":
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "left"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "right"
                break

    if head_y - 1 < 0:
        direction == "left"
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "right"
                break

if direction == "down":
    if food_dir == "left":
        direction = "left"
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "down"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y + 1:
                direction == "right"
                break

    if food_dir == "right":
        direction = "right"
        for segment in snake.segments:
            if segment.X // 32 == head_x + 1:
                direction == "down"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y + 1:
                direction == "left"
                break

    if food_dir == "down":
        for segment in snake.segments:
            if segment.Y // 32 == head_y + 1:
                direction == "left"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "right"
                break

    if head_y + 1 >= 18:
        direction == "left"
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "right"
                break

if direction == "left":
    print("llllll")
    if food_dir == "up":
        direction = "up"
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "left"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "down"
                break

    if food_dir == "down":
        direction = "down"
        for segment in snake.segments:
            if segment.Y // 32 == head_y + 1:
                direction == "left"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "up"
                break

    if food_dir == "left":
        for segment in snake.segments:
            if segment.X // 32 == head_x - 1:
                direction == "up"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "down"
                break

    if head_x - 1 < 0:
        direction == "up"
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "down"
                break

if direction == "right":
    if food_dir == "up":
        direction = "up"
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "right"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x + 1:
                direction == "down"
                break

    if food_dir == "down":
        direction = "down"
        for segment in snake.segments:
            if segment.Y // 32 == head_y + 1:
                direction == "right"
                break
        for segment in snake.segments:
            if segment.X // 32 == head_x + 1:
                direction == "up"
                break

    if food_dir == "right":
        for segment in snake.segments:
            if segment.X // 32 == head_x + 1:
                direction == "up"
                break
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "down"
                break

    if head_x + 1 >= 24:
        direction == "up"
        for segment in snake.segments:
            if segment.Y // 32 == head_y - 1:
                direction == "down"
                break

#set velocity based on direction
if direction == "up": snake.velocity = Point(0,-1)
elif direction == "down": snake.velocity = Point(0,1)
elif direction == "left": snake.velocity = Point(-1,0)
elif direction == "right": snake.velocity = Point(1,0)

this function initializes the game

def game_init():
global screen, backbuffer, font, timer, snake, food_group

pygame.init()
screen = pygame.display.set_mode((24 \* 32,18 \* 32))
pygame.display.set_caption("Snake Game")
font = pygame.font.Font(None, 30)
timer = pygame.time.Clock()

#create a drawing surface
backbuffer = pygame.Surface((screen.get_rect().width,screen.get_rect().height))

#create snake
snake = Snake()
image = pygame.Surface((60,60)).convert_alpha()
image.fill((255,255,255,0))
pygame.draw.circle(image, (80,80,220,70), (30,30), 30, 0)
pygame.draw.circle(image, (80,80,250,255), (30,30), 30, 4)

#create food
food_group = pygame.sprite.Group()
food = Food()
food_group.add(food)

main program begins

game_init()
game_over = False
last_time = 0

auto_play = False #additional code added
step_time = 400

main loop

while True:
timer.tick(30)
ticks = pygame.time.get_ticks()

#event section
for event in pygame.event.get():
    if event.type == QUIT: sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]: sys.exit()
elif keys[K_UP] or keys[K_w]:
    snake.velocity = Point(0,-1)
elif keys[K_DOWN] or keys[K_s]:
    snake.velocity = Point(0,1)
elif keys[K_LEFT] or keys[K_a]:
    snake.velocity = Point(-1,0)
elif keys[K_RIGHT] or keys[K_d]:
    snake.velocity = Point(1,0)
elif keys[K_SPACE]: #additional code added
    if auto_play:
        auto_play = False
        step_time = 400
    else:
        auto_play = True
        step_time = 50

#update section
if not game_over:
    snake.update(ticks)
    food_group.update(ticks)
    
    #try to pick up food
    hit_list = pygame.sprite.groupcollide(snake.segments, \
        food_group, False, True)
    if len(hit_list) > 0:
        food_group.add(Food())
        snake.add_segment()

    #see if head collides with body
    for n in range(1, len(snake.segments)):
        if pygame.sprite.collide_rect(snake.segments[0], snake.segments[n]):
            game_over = True

    #check screen boundary
    head_x = snake.segments[0].X//32
    head_y = snake.segments[0].Y//32
    if head_x < 0 or head_x > 24 or head_y < 0 or head_y > 18:
        game_over = True

    #additional code added
    if auto_play: auto_move()


#drawing section
backbuffer.fill((20,50,20)) 
snake.draw(backbuffer)
food_group.draw(backbuffer)
screen.blit(backbuffer, (0,0))

if not game_over:
    print_text(font, 0, 0, "Length " + str(len(snake.segments)))
    print_text(font, 0, 20, "Position " + str(snake.segments[0].X//32) + \
               "," + str(snake.segments[0].Y//32))
else:
    print_text(font, 0, 0, "GAME OVER")

#additional code added
if auto_play: 
    print_text(font, 700, 0, "AUTO")
    

pygame.display.update() 

</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容