用Python写贪吃蛇
时间: 2023-11-19 15:09:18 浏览: 68
作为AI,我可以帮您提供Python贪吃蛇的代码,如下所示:
```
import pygame
import random
pygame.init()
# 游戏窗口
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WINDOW_TITLE = '贪吃蛇'
WINDOW_COLOR = (255, 255, 255)
# 蛇
SNAKE_SIZE = 10
SNAKE_COLOR = (0, 255, 0)
SNAKE_SPEED = 10
# 食物
FOOD_SIZE = 10
FOOD_COLOR = (255, 0, 0)
# 初始化游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(WINDOW_TITLE)
window.fill(WINDOW_COLOR)
# 初始化蛇
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2
snake_body = [[snake_x, snake_y], [snake_x - SNAKE_SIZE, snake_y], [snake_x - (2 * SNAKE_SIZE), snake_y]]
snake_direction = 'RIGHT'
# 随机生成食物的位置
food_x = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
food_y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)
# 游戏循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'RIGHT':
snake_direction = 'LEFT'
elif event.key == pygame.K_RIGHT and snake_direction != 'LEFT':
snake_direction = 'RIGHT'
elif event.key == pygame.K_UP and snake_direction != 'DOWN':
snake_direction = 'UP'
elif event.key == pygame.K_DOWN and snake_direction != 'UP':
snake_direction = 'DOWN'
# 移动蛇的身体
if snake_direction == 'RIGHT':
snake_x += SNAKE_SPEED
elif snake_direction == 'LEFT':
snake_x -= SNAKE_SPEED
elif snake_direction == 'UP':
snake_y -= SNAKE_SPEED
elif snake_direction == 'DOWN':
snake_y += SNAKE_SPEED
# 判断是否吃到了食物
if snake_x <= food_x + FOOD_SIZE and snake_x >= food_x and snake_y <= food_y + FOOD_SIZE and snake_y >= 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])
# 删除蛇的尾巴
snake_body.pop(0)
# 添加蛇的头部
snake_body.append([snake_x, snake_y])
# 判断蛇是否撞到了边界
if snake_x < 0 or snake_x > WINDOW_WIDTH or snake_y < 0 or snake_y > WINDOW_HEIGHT:
game_over = True
# 判断蛇是否撞到了自己
for i in range(0, len(snake_body) - 1):
if snake_body[i] == [snake_x, snake_y]:
game_over = True
# 绘制游戏窗口
window.fill(WINDOW_COLOR)
pygame.draw.rect(window, FOOD_COLOR, [food_x, food_y, FOOD_SIZE, FOOD_SIZE])
for i in range(0, len(snake_body)):
pygame.draw.rect(window, SNAKE_COLOR, [snake_body[i][0], snake_body[i][1], SNAKE_SIZE, SNAKE_SIZE])
pygame.display.update()
pygame.quit()
```
运行以上代码,即可在Python中实现一个简单的贪吃蛇游戏。
阅读全文