在学习了基础的Pygame后,我们终于要开始学习制作我们的游戏了。我们第一个要制作的游戏很简单,这个游戏很简单,它的名字叫做Pie游戏。玩家按一二三四四个键以完成一个饼块,完成后饼就会变绿,以示游戏完成。虽然逻辑很简单,但是它也可以成为你学习Pygame的一个里程碑。好了,咱们话不多说,赶紧开始我们的Pygame之旅吧!
目录
1 初始化
输入以下代码:
# 导入所需模块
import pygame
from pygame.locals import *
import sys
# 初始化
pygame.init()
对Pygame的初始化就完成了。
2 绘制饼块,数字
screen = pygame.display.set_mode((600, 500))
my_font = pygame.font.Font(None, 60)
pygame.display.set_caption("The Pie game---press 1/2/3/4")
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
try:
while True:
# 渲染屏幕
screen.fill((0, 0, 200))
# 绘制数字
Text_Image1 = my_font.render("1", True, color)
Text_Image2 = my_font.render("2", True, color)
Text_Image3 = my_font.render("3", True, color)
Text_Image4 = my_font.render("4", True, color)
screen.blit(Text_Image1, (x + radius / 2 - 200, y - radius / 2))
screen.blit(Text_Image2, (x + radius / 2, y - radius / 2))
screen.blit(Text_Image3, (x + radius / 2, y - radius / 2 + 160))
screen.blit(Text_Image4, (x + radius / 2 - 200, y - radius / 2 + 160))
# 饼块是否完成
if piece1:
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 piece2:
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 piece3:
start_angle = math.radians(270)
end_angle = math.radians(0)
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(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)
pygame.display.update()
其中参数介绍:
pygame.draw.arc(surface, color, rect, start_angle, stop_angle)
# surface ->在哪个屏幕上绘制
# color -> 颜色
# rect -> 在哪个矩形中绘制
# start_angle -> 起始弧度(用math.radians()函数将角度转为弧度)
# end_angle -> 结束弧度
pygame.draw.line(surface, color, start_pos, end_pos)
# surface ->在哪个屏幕上绘制
# color -> 颜色
# start_angle -> 起始坐标
# end_angle -> 结束坐标
3 程序逻辑部分
在上章的循环后加上这样一段代码:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit()
if event.key == K_1:
piece1 = True
if event.key == K_2:
piece2 = True
if event.key == K_3:
piece3 = True
if event.key == K_4:
piece4 = True
if piece1 and piece2 and piece3 and piece4:
color = 0, 255, 0
这个程序的逻辑部分就完成了。