﻿ Program Arcade Games With Python And Pygame

# Program Arcade GamesWith Python And Pygame

 < Previous Home Next >

# Chapter 10: 控制器和图形

## 10.1 入门

def draw_snowman(screen, x, y):
# 画一个圆形作头部
pygame.draw.ellipse(screen, WHITE, [35+x, 0+y, 25, 25])
# 画一个圆形作中部
pygame.draw.ellipse(screen, WHITE, [23+x, 20+y, 50, 50])
# 画一个圆形作底部
pygame.draw.ellipse(screen, WHITE, [0+x, 65+y, 100, 100])


# 左上角的雪人
draw_snowman(screen, 10, 10)

# 右上角的雪人
draw_snowman(screen, 300, 10)

# 左下角的雪人
draw_snowman(screen, 10, 300)


# 头
pygame.draw.ellipse(screen, BLACK, [96,83,10,10], 0)

# 腿
pygame.draw.line(screen, BLACK, [100,100], [105,110], 2)
pygame.draw.line(screen, BLACK, [100,100], [95,110], 2)

# 身体
pygame.draw.line(screen, RED, [100,100], [100,90], 2)

# 手臂
pygame.draw.line(screen, RED, [100,90], [104,100], 2)
pygame.draw.line(screen, RED, [100,90], [96,100], 2)


def draw_stick_figure(screen,x,y):
# 头
pygame.draw.ellipse(screen, BLACK, [96,83,10,10], 0)

# 腿
pygame.draw.line(screen, BLACK, [100,100], [105,110], 2)
pygame.draw.line(screen, BLACK, [100,100], [95,110], 2)

# 身体
pygame.draw.line(screen, RED, [100,100], [100,90], 2)

# 手臂
pygame.draw.line(screen, RED, [100,90], [104,100], 2)
pygame.draw.line(screen, RED, [100,90], [96,100], 2)


def draw_stick_figure(screen, x, y):
# 头
pygame.draw.ellipse(screen, BLACK,[96+x,83+y,10,10],0)

# 腿
pygame.draw.line(screen, BLACK, [100+x,100+y], [105+x,110+y], 2)
pygame.draw.line(screen, BLACK, [100+x,100+y], [95+x,110+y], 2)

# 身体
pygame.draw.line(screen, RED, [100+x,100+y], [100+x,90+y], 2)

# 手臂
pygame.draw.line(screen, RED, [100+x,90+y], [104+x,100+y], 2)
pygame.draw.line(screen, RED, [100+x,90+y], [96+x,100+y], 2)


draw_stick_figure(screen, 50, 50)


def draw_stick_figure(screen, x, y):
# 头
pygame.draw.ellipse(screen, BLACK,[96-95+x,83-83+y,10,10],0)

# 腿
pygame.draw.line(screen, BLACK, [100-95+x,100-83+y], [105-95+x,110-83+y], 2)
pygame.draw.line(screen, BLACK, [100-95+x,100-83+y], [95-95+x,110-83+y], 2)

# 身体
pygame.draw.line(screen, RED, [100-95+x,100-83+y], [100-95+x,90-83+y], 2)

# 手臂
pygame.draw.line(screen, RED, [100-95+x,90-83+y], [104-95+x,100-83+y], 2)
pygame.draw.line(screen, RED, [100-95+x,90-83+y], [96-95+x,100-83+y], 2)


def draw_stick_figure(screen, x, y):
# 头
pygame.draw.ellipse(screen, BLACK, [1+x,y,10,10], 0)

# 腿
pygame.draw.line(screen, BLACK ,[5+x,17+y], [10+x,27+y], 2)
pygame.draw.line(screen, BLACK, [5+x,17+y], [x,27+y], 2)

# 身体
pygame.draw.line(screen, RED, [5+x,17+y], [5+x,7+y], 2)

# 手臂
pygame.draw.line(screen, RED, [5+x,7+y], [9+x,17+y], 2)
pygame.draw.line(screen, RED, [5+x,7+y], [1+x,17+y], 2)


## 10.2 鼠标

pos = pygame.mouse.get_pos()


# 游戏逻辑
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]

# 绘图
draw_stick_figure(screen, x, y)


# 隐藏鼠标光标
pygame.mouse.set_visible(False)


## 10.3 键盘

• 创建一个对初始的x和y作为起点。
• 当方向键按下的时候，设置一个每帧的“速度”，以像素表示。
• 当方向键释放的时候，把这个速度重新设为0。
• 根据不同的速度调整每一帧的x，y。

# 每一帧的速度
x_speed = 0
y_speed = 0

# 闲杂的位置现在x_coord = 10
y_coord = 10


for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

# 用户按下了一个键
if event.type == pygame.KEYDOWN:
# 判断出是一个方向键，从而调整速度。
if event.key == pygame.K_LEFT:
x_speed = -3
if event.key == pygame.K_RIGHT:
x_speed = 3
if event.key == pygame.K_UP:
y_speed = -3
if event.key == pygame.K_DOWN:
y_speed = 3

# 用户释放了一个键
if event.type == pygame.KEYUP:
# 判断出是一个方向键，从而重设速度为0。
if event.key == pygame.K_LEFT:
x_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = 0
if event.key == pygame.K_UP:
y_speed = 0
if event.key == pygame.K_DOWN:
y_speed = 0

# 根据速度矢量来移动物体
x_coord += x_speed
y_coord += y_speed

# 画出图像
draw_stick_figure(screen, x_coord, y_coord)


Pygame码ASCII常用名称
K_BACKSPACE\bbackspace
K_RETURN\rreturn
K_TAB\ttab
K_ESCAPE^[escape
K_SPACE space
K_COMMA,comma sign
K_MINUS-minus
K_PERIOD.period slash
K_SLASH/forward
K_000
K_111
K_222
K_333
K_444
K_555
K_666
K_777
K_888
K_999
K_SEMICOLON;semicolon sign
K_EQUALS=equals sign
K_LEFTBRACKET[left
K_RIGHTBRACKET]right
K_BACKSLASH\backslash bracket
K_BACKQUOTEgrave
K_aaa
K_bbb
K_ccc
K_ddd
K_eee
K_fff
K_ggg
K_hhh
K_iii
K_jjj
K_kkk
K_lll
K_mmm
K_nnn
K_ooo
K_ppp
K_qqq
K_rrr
K_sss
K_ttt
K_uuu
K_vvv
K_www
K_xxx
K_yyy
K_zzz
K_DELETEdelete
K_UPuparrow
K_DOWNdownarrow
K_RIGHTrightarrow
K_LEFTleftarrow
K_INSERTinsert
K_HOMEhome
K_ENDend
K_PAGEUPpageup
K_PAGEDOWNpagedown
K_F1F1
K_F2F2
K_F3F3
K_F4F4
K_F5F5
K_F6F6
K_F7F7
K_F8F8
K_F9F9
K_F10F10
K_F11F11
K_F12F12
K_NUMLOCKnumlock
K_CAPSLOCKcapslock
K_RSHIFTrightshift
K_LSHIFTleftshift
K_RCTRLrightctrl
K_LCTRLleftctrl
K_RALTrightalt
K_LALTleftalt

## 10.4 游戏控制器

# 现在位置
x_coord = 10
y_coord = 10

# 检查游戏手柄
joystick_count = pygame.joystick.get_count()
if joystick_count == 0:
# 没检查到游戏手柄！
print("Error, I didn't find any joysticks.")
else:
# 使用手柄0并初始化
my_joystick = pygame.joystick.Joystick(0)
my_joystick.init()


# 这需在主循环之中

#检查手柄的存在
if joystick_count != 0:

# 获得手柄的位置
# 返回一个-1.0 and +1.0之间的值
horiz_axis_pos = my_joystick.get_axis(0)
vert_axis_pos = my_joystick.get_axis(1)

#沿着轴移动x。乘以10来加速。
# 转化成整数，因为我们不能在像素3.5处画图，要么像素3或是像素4。
x_coord = x_coord + int(horiz_axis_pos * 10)
y_coord = y_coord + int(vert_axis_pos * 10)

# 清理屏幕
screen.fill(WHITE)

# 在适当的位置绘图
draw_stick_figure(screen, x_coord, y_coord)


"""
Sample Python/Pygame Programs
Simpson College Computer Science
http://simpson.edu/computer-science/

Show everything we can pull off the joystick
"""
import pygame

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class TextPrint(object):
"""
This is a simple class that will help us print to the screen
It has nothing to do with the joysticks, just outputting the
information.
"""
def __init__(self):
""" Constructor """
self.reset()
self.x_pos = 10
self.y_pos = 10
self.font = pygame.font.Font(None, 20)

def print(self, my_screen, text_string):
""" Draw text onto the screen. """
text_bitmap = self.font.render(text_string, True, BLACK)
my_screen.blit(text_bitmap, [self.x_pos, self.y_pos])
self.y_pos += self.line_height

def reset(self):
""" Reset text to the top of the screen. """
self.x_pos = 10
self.y_pos = 10
self.line_height = 15

def indent(self):
""" Indent the next line of text """
self.x_pos += 10

def unindent(self):
""" Unindent the next line of text """
self.x_pos -= 10

pygame.init()

# Set the width and height of the screen [width,height]
size = [500, 700]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Initialize the joysticks
pygame.joystick.init()

textPrint = TextPrint()

# -------- Main Program Loop -----------
while not done:
# EVENT PROCESSING STEP
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

# Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN
# JOYBUTTONUP JOYHATMOTION
if event.type == pygame.JOYBUTTONDOWN:
print("Joystick button pressed.")
if event.type == pygame.JOYBUTTONUP:
print("Joystick button released.")

# DRAWING STEP
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
textPrint.reset()

# Get count of joysticks
joystick_count = pygame.joystick.get_count()

textPrint.print(screen, "Number of joysticks: {}".format(joystick_count))
textPrint.indent()

# For each joystick:
for i in range(joystick_count):
joystick = pygame.joystick.Joystick(i)
joystick.init()

textPrint.print(screen, "Joystick {}".format(i))
textPrint.indent()

# Get the name from the OS for the controller/joystick
name = joystick.get_name()
textPrint.print(screen, "Joystick name: {}".format(name))

# Usually axis run in pairs, up/down for one, and left/right for
# the other.
axes = joystick.get_numaxes()
textPrint.print(screen, "Number of axes: {}".format(axes))
textPrint.indent()

for i in range(axes):
axis = joystick.get_axis(i)
textPrint.print(screen, "Axis {} value: {:>6.3f}".format(i, axis))
textPrint.unindent()

buttons = joystick.get_numbuttons()
textPrint.print(screen, "Number of buttons: {}".format(buttons))
textPrint.indent()

for i in range(buttons):
button = joystick.get_button(i)
textPrint.print(screen, "Button {:>2} value: {}".format(i, button))
textPrint.unindent()

# Hat switch. All or nothing for direction, not like joysticks.
# Value comes back in an array.
hats = joystick.get_numhats()
textPrint.print(screen, "Number of hats: {}".format(hats))
textPrint.indent()

for i in range(hats):
hat = joystick.get_hat(i)
textPrint.print(screen, "Hat {} value: {}".format(i, str(hat)))
textPrint.unindent()

textPrint.unindent()

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Limit to 60 frames per second
clock.tick(60)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

`