写一个简单的Python贪吃蛇代码
时间: 2024-03-21 17:16:15 浏览: 54
好的,以下是一个简单的Python贪吃蛇代码:
```python
import pygame
import random
# 设置窗口大小
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
# 设置蛇的大小和速度
SNAKE_SIZE = 20
SNAKE_SPEED = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 初始化pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置
snake_x = SCREEN_WIDTH / 2
snake_y = SCREEN_HEIGHT / 2
# 定义蛇的初始长度和方向
snake_length = 1
snake_direction = "right"
# 定义食物的初始位置
food_x = random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE, SNAKE_SIZE)
food_y = random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE, SNAKE_SIZE)
# 游戏循环
while True:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 处理键盘事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and snake_direction != "right":
snake_direction = "left"
elif keys[pygame.K_RIGHT] and snake_direction != "left":
snake_direction = "right"
elif keys[pygame.K_UP] and snake_direction != "down":
snake_direction = "up"
elif keys[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 and snake_y == food_y:
snake_length += 1
food_x = random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE, SNAKE_SIZE)
food_y = random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE, SNAKE_SIZE)
# 绘制游戏界面
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, [food_x, food_y, SNAKE_SIZE, SNAKE_SIZE])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list = []
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list:
pygame.draw.rect(screen, WHITE, [segment[0], segment[1], SNAKE_SIZE, SNAKE_SIZE])
# 刷新窗口
pygame.display.update()
```
这是一个基本的贪吃蛇游戏代码,可以在pygame环境下运行。
阅读全文