用Python写一段贪吃蛇代码
时间: 2023-11-19 19:39:58 浏览: 80
这是一段Python代码,可以用来编写贪吃蛇游戏:import pygame
import random
import sys# 窗口大小
SIZE = (600, 600)# 背景颜色
BG_COLOR = (255, 255, 255)# 蛇的颜色
SNAKE_COLOR = (0, 0, 0)# 食物的颜色
FOOD_COLOR = (255, 0, 0)# 初始化pygame
pygame.init()# 初始化窗口
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption('贪吃蛇')# 定义蛇的移动方向
UP = (0, -10)
DOWN = (0, 10)
LEFT = (-10, 0)
RIGHT = (10, 0)# 初始化蛇的坐标
snake = [(200, 200), (210, 200), (220, 200)]# 初始化食物坐标
food = (random.randint(0, SIZE[0]-10), random.randint(0, SIZE[1]-10))# 设置初始化方向
direction = RIGHT# 游戏的主循环
while True:
# 将背景设置为白色
screen.fill(BG_COLOR) # 绘制蛇
for pos in snake:
pygame.draw.rect(screen, SNAKE_COLOR, pygame.Rect(pos[0], pos[1], 10, 10)) # 绘制食物
pygame.draw.rect(screen, FOOD_COLOR, pygame.Rect(food[0], food[1], 10, 10)) # 更新蛇的位置
for i in range(len(snake)-1, 0, -1):
snake[i] = (snake[i-1][0], snake[i-1][1]) # 更新蛇头的位置
snake[0] = (snake[0][0] + direction[0], snake[0][1] + direction[1]) # 判断是否吃掉了食物
if snake[0] == food:
food = (random.randint(0, SIZE[0]-10), random.randint(0, SIZE[1]-10))
snake.append((0, 0)) # 判断是否碰到了边界
if snake[0][0] == SIZE[0] or snake[0][0] < 0 or snake[0][1] == SIZE[1] or snake[0][1] < 0:
sys.exit() # 监听键盘事件
for event in pygame.event.get():
# 监听到退出事件后,退出程序
if event.type == pygame.QUIT:
sys.exit() # 监听到按键按下时
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != DOWN:
direction = UP
if event.key == pygame.K_DOWN and direction != UP:
direction = DOWN
if event.key == pygame.K_LEFT and direction != RIGHT:
direction = LEFT
if event.key == pygame.K_RIGHT and direction != LEFT:
direction = RIGHT # 更新界面
pygame.display.update()
阅读全文