请用python帮我写一个贪吃蛇的代码
时间: 2023-08-20 07:14:48 浏览: 160
好的,以下是一个简单的贪吃蛇的Python代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏界面大小
width = 600
height = 400
# 创建游戏界面
screen = pygame.display.set_mode((width, height))
# 设置游戏界面标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 定义蛇的初始位置和大小
snake_size = 10
snake_x = width / 2
snake_y = height / 2
# 定义蛇的移动速度
snake_speed = 5
# 定义食物的初始位置和大小
food_size = 10
food_x = round(random.randrange(0, width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - food_size) / 10.0) * 10.0
# 定义蛇的移动方向
snake_direction = "right"
# 定义游戏结束标志
game_over = False
# 创建时钟对象
clock = pygame.time.Clock()
# 定义绘制蛇的函数
def draw_snake(snake_list):
for x,y in snake_list:
pygame.draw.rect(screen, green, [x, y, snake_size, snake_size])
# 开始游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 处理键盘输入事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_direction = "left"
elif keys[pygame.K_RIGHT]:
snake_direction = "right"
elif keys[pygame.K_UP]:
snake_direction = "up"
elif keys[pygame.K_DOWN]:
snake_direction = "down"
# 移动蛇
if snake_direction == "left":
snake_x -= snake_speed
elif snake_direction == "right":
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:
food_x = round(random.randrange(0, width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - food_size) / 10.0) * 10.0
# 绘制游戏界面
screen.fill(black)
pygame.draw.rect(screen, red, [food_x, food_y, food_size, food_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list = []
snake_list.append(snake_head)
draw_snake(snake_list)
pygame.display.update()
# 控制游戏帧率
clock.tick(30)
# 退出游戏
pygame.quit()
quit()
```
这段代码创建了一个简单的游戏界面,定义了蛇的初始位置、大小和移动速度,食物的初始位置和大小,以及游戏结束标志。游戏循环中处理游戏事件和键盘输入事件,移动蛇,判断蛇是否吃到食物,绘制游戏界面,并控制游戏帧率。
阅读全文