给我写一个python贪吃蛇代码
时间: 2023-05-30 15:05:26 浏览: 114
以下是一个简单的Python贪吃蛇代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
GAME_WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置游戏标题
pygame.display.set_caption('Python贪吃蛇')
# 定义颜色变量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义贪吃蛇初始位置和大小
SNAKE_SIZE = 10
SNAKE_X = 100
SNAKE_Y = 100
# 定义食物初始位置
FOOD_SIZE = 10
FOOD_X = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
FOOD_Y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)
# 定义贪吃蛇移动速度
SNAKE_SPEED = 10
# 定义贪吃蛇初始移动方向
MOVE_DIRECTION = 'right'
# 定义贪吃蛇身体坐标列表
snake_body = [(SNAKE_X, SNAKE_Y)]
# 定义游戏循环标志
game_over = False
# 定义游戏循环
while not game_over:
# 检测游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and MOVE_DIRECTION != 'down':
MOVE_DIRECTION = 'up'
elif event.key == pygame.K_DOWN and MOVE_DIRECTION != 'up':
MOVE_DIRECTION = 'down'
elif event.key == pygame.K_LEFT and MOVE_DIRECTION != 'right':
MOVE_DIRECTION = 'left'
elif event.key == pygame.K_RIGHT and MOVE_DIRECTION != 'left':
MOVE_DIRECTION = 'right'
# 根据移动方向更新贪吃蛇位置
if MOVE_DIRECTION == 'up':
SNAKE_Y -= SNAKE_SPEED
elif MOVE_DIRECTION == 'down':
SNAKE_Y += SNAKE_SPEED
elif MOVE_DIRECTION == 'left':
SNAKE_X -= SNAKE_SPEED
elif MOVE_DIRECTION == 'right':
SNAKE_X += SNAKE_SPEED
# 判断贪吃蛇是否吃到食物
if SNAKE_X < FOOD_X + FOOD_SIZE and SNAKE_X + SNAKE_SIZE > FOOD_X and SNAKE_Y < FOOD_Y + FOOD_SIZE and SNAKE_Y + SNAKE_SIZE > FOOD_Y:
# 更新食物位置
FOOD_X = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
FOOD_Y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)
# 在贪吃蛇身体列表中添加一个新的坐标
snake_body.append((SNAKE_X, SNAKE_Y))
# 在游戏窗口中绘制贪吃蛇和食物
GAME_WINDOW.fill(BLACK)
pygame.draw.rect(GAME_WINDOW, GREEN, (FOOD_X, FOOD_Y, FOOD_SIZE, FOOD_SIZE))
for body_part in snake_body:
pygame.draw.rect(GAME_WINDOW, WHITE, (body_part[0], body_part[1], SNAKE_SIZE, SNAKE_SIZE))
# 更新贪吃蛇身体坐标列表
snake_body.insert(0, (SNAKE_X, SNAKE_Y))
snake_body.pop()
# 判断贪吃蛇是否碰到边界或自己
if SNAKE_X < 0 or SNAKE_X > WINDOW_WIDTH - SNAKE_SIZE or SNAKE_Y < 0 or SNAKE_Y > WINDOW_HEIGHT - SNAKE_SIZE:
game_over = True
for body_part in snake_body[1:]:
if SNAKE_X == body_part[0] and SNAKE_Y == body_part[1]:
game_over = True
# 更新游戏窗口显示
pygame.display.update()
# 退出pygame
pygame.quit()
```
阅读全文