PYGAME EXAMPLE

import math

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>

 import os  import tempfile  import time  from functoole import reduce  from PIL import Image  BACKGROUND_POS = {40,500}  DISTANCE_TO_TIME_RATIO =1.35  SCREENSHOT_PATH = tempfile.gettempdir()+”/screenshot.png”  def calculate_jump_distance():      im =Image.open(SCREENSHOT_PATE)      baxkround_rgb = im.getpixel(BACKGROUND_POS)       role_pos_list = None     vertex1_pos = None     block_background_rgb = None     vertex2_pos = None     role_line_flag = True     for y in range(BACKGROUND_POS[1], im.height):         if role_pos_list and role_line_flag:             break         role_line_flag = True         vertex2_line_flag = True         for x in range(BACKGROUND_POS[0], im.width):             current_rgb = im.getpixel((x, y))             next_rgb = im.getpixel((x + 1, y)) if x + 1 < im.width else (0, 0, 0)             # 识别顶点1             if x > BACKGROUND_POS[0] and y > BACKGROUND_POS[1] and not vertex1_pos                      and not is_similar(background_rgb, current_rgb) and is_similar(current_rgb, next_rgb):                 vertex1_pos = (x, y)                 block_background_rgb = current_rgb             # 识别顶点2             if block_background_rgb and vertex2_line_澳门新葡亰游戏网址,flag and is_similar(current_rgb, block_background_rgb, 5):                 vertex2_line_flag = False                 if vertex2_pos:                     if x < vertex2_pos[0] and vertex2_pos[0] – x < 20 and y – vertex2_pos[1] < 20:                         vertex2_pos = (x, y)                 else:                     vertex2_pos = (x, y)             # 识别小人             if is_part_of_role(current_rgb):                 if role_line_flag:                     role_pos_list = []                     role_line_flag = False                 role_pos_list.append((x, y))     if len(role_pos_list) == 0:         raise Exception(‘无法识别小人位置!!!’)     pos_sum = reduce((lambda o1, o2: (o1[0] + o2[0], o1[1] + o2[1])), role_pos_list)     role_pos = (int(pos_sum[0] / len(role_pos_list)), int(pos_sum[1] / len(role_pos_list)))     destination_pos = (vertex1_pos[0], vertex2_pos[1])     return int(linear_distance(role_pos, destination_pos)) def is_part_of_role(rgb):     return 53 < rgb[0] < 59 and 57 < rgb[1] < 61 and 95 < rgb[2] < 103 def linear_distance(xy1, xy2):     return math.sqrt(pow(xy1[0] – xy2[0], 2) + pow(xy1[1] – xy2[1], 2)) def is_similar(rgb1, rgb2, degree=10):     return abs(rgb1[0] – rgb2[0]) <= degree and abs(rgb1[1] – rgb2[1]) <= degree and abs(rgb1[2] – rgb2[2]) <= degree def screenshot():     os.system(“adb shell screencap -p /mnt/sdcard/screencap.png”)     os.system(“adb pull /mnt/sdcard/screencap.png {} >> {}/jump.out”.format(SCREENSHOT_PATH, tempfile.gettempdir())) def jump(touch_time):     os.system(“adb shell input swipe 0 0 0 0 {}”.format(touch_time)) def distance2time(distance):     return int(distance * DISTANCE_TO_TIME_RATIO) if __name__ == ‘__main__’:     count = 1     while True:         screenshot()         distance = calculate_jump_distance()         touch_time = distance2time(distance)         jump(touch_time)         print(“#{}: distance={}, time={}”.format(count, distance, touch_time))         count += 1         time.sleep(1)

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()

网站地图xml地图