Commit 61fe8974 by BellCodeEditor

auto save

parent 65170d4f
Showing with 48 additions and 8 deletions
......@@ -6,28 +6,68 @@ pygame.init()
# 创建一个窗口
screen = pygame.display.set_mode((660, 480))
FPSCLOCK = pygame.time.Clock() # pygame时钟,控制游戏速度(帧数)
# 背景
background = pygame.image.load('bg.png')
right = pygame.image.load('right.png')
right = pygame.image.load('right.png') # 头朝右
food = pygame.image.load('apple.png')
body = pygame.image.load('body.png')
left = pygame.image.load('left.png') # 朝左
up = pygame.image.load('up.png') # 朝上
down = pygame.image.load('down.png') # 朝下
x, y = 240, 120 # 初始化贪吃蛇头的坐标设置x,y为240,120
# 创建列表储存贪吃蛇的初始坐标三段身体以及蛇头坐标
position = [(180, 90), (180, 120), (210, 120), (x, y)]
setheading = "right" # 新建变量setheading记录贪吃蛇朝向并设为朝右"right"
snake_head = right # 新建变量snake_head用来设置贪吃蛇朝向造型,初始造型设为朝右
while True:
for event in pygame.event.get():
if event.type == locals.QUIT:
# 接收到退出事件后退出程序
exit()
if event.type == locals.KEYDOWN: # if判断键盘是否被按下
# if判断四个方向建是否被按下以及判断贪吃蛇朝向是否相反
# 就将方向设为按下方向键朝向
# 将造型设置为朝向造型
if event.key == locals.K_RIGHT and setheading != "left":
setheading = 'right'
snake_head = right
if event.key == locals.K_LEFT and setheading != "right":
setheading = 'left'
snake_head = left
if event.key == locals.K_UP and setheading != "down":
setheading = 'up'
snake_head = up
if event.key == locals.K_DOWN and setheading != "up":
setheading = 'down'
snake_head = down
# 设置贪吃蛇的头部坐标
if setheading == "right": # if判断朝向向右
x += 30 # x坐标增加一格
elif setheading == "left": # 继续判断朝向向左
x -= 30 # x坐标减少一格
elif setheading == "up": # 继续判断朝向向上
y -= 30 # y坐标减少一格
else: # 否则
y += 30 # y坐标增加一格
# 将贪吃蛇头的新坐标追加进列表
position.append((x, y))
position.pop(0)
# 将背景图画上去
screen.blit(background, (0, 0))
# 将贪吃蛇的头画上去
screen.blit(right, (x, y))
screen.blit(snake_head, position[-1]) # 将列表的第一个元素删除作为蛇头的坐标
# 将贪吃蛇的身体画上去
screen.blit(body, (210, 120))
screen.blit(body, (180, 120))
screen.blit(body, (180, 90))
# for循环取出身体坐标len()获取列表长度-1,得到的值通过range()函数生成列表下标
for i in range(len(position)-1):
screen.blit(body, position[i]) # 取出列表里所有身体坐标进行渲染
# 将果实画上去
screen.blit(food, (360, 300))
# 刷新画面
pygame.display.update()
\ No newline at end of file
pygame.display.update()
FPSCLOCK.tick(3) # 用计时器的tick()方法设置帧数为3
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment