pygame-贪吃蛇小游戏
写一个贪吃蛇小游戏。
代码如下:
import pygame
import random
pygame.init()
# 界说窗口轻重
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(“贪吃蛇”)
# 界说颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 界说蛇和食品的初始地点和轻重
snake_block = 10
food_block = 10
snake = [[width // 2, height // 2], [width // 2 – snake_block, height // 2], [width // 2 – snake_block * 2, height // 2]]
food = [random.randint(0, width // snake_block – 1) * snake_block, random.randint(0, height // snake_block – 1) * snake_block]
# 游戏主循环
running = Truewhile running:
# 处理事变行列
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = [0, -snake_block]
elif event.key == pygame.K_DOWN:change_to = [0, snake_block]
elif event.key == pygame.K_LEFT:
change_to = [-snake_block, 0]
elif event.key ==pygame.K_RIGHT:change_to = [snake_block, 0]
else:change_to = [0, 0]
else:change_to = [0, 0]
head = snake[0] # 获取蛇头地点
new_head = (head[0] + change_to[0], head[1] + change_to[1]) # 更新蛇头地点
if new_head in snake and change_to != [0, 0]: # 假如蛇头撞到本人,游戏完毕
running = False
snake.insert(0, list(new_head)) # 将新蛇头添加到蛇的开头
if len(snake) > width // snake_block and snake[1] in snake[2:]: # 假如蛇肢体相撞,游戏完毕
running = False
if new_head == food:
food = [random.randint(0, width // snake_block – 1) * snake_block, random.randint(0, height // snake_block – 1) * snake_block]
snake.append(list(new_head))
else:
snake.pop()
screen.fill(WHITE)
for segment in snake:
pygame.draw.rect(screen, GREEN, (segment[0], segment[1], snake_block, snake_block))
pygame.draw.rect(screen, RED, (food[0], food[1], snake_block, snake_block)) # 绘制食品
pygame.display.flip()
pygame.time.delay(100)