写一个贪吃蛇游戏代码,python
时间: 2024-02-18 11:31:17 浏览: 116
贪吃蛇游戏代码,Python
好的,下面是一个简单的贪吃蛇游戏的代码,使用 Python 语言编写:
```
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口的大小
screen_width = 480
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的方向常量
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 定义蛇的颜色和大小
snake_color = (0, 255, 0)
snake_size = 20
# 定义食物的颜色和大小
food_color = (255, 0, 0)
food_size = 20
# 定义游戏的帧率
clock = pygame.time.Clock()
fps = 10
# 定义蛇的初始位置和方向
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_direction = random.randint(0, 3)
# 定义蛇的初始长度和身体坐标列表
snake_length = 1
snake_body = [(snake_x, snake_y)]
# 定义食物的初始位置
food_x = random.randint(snake_size, screen_width - food_size)
food_y = random.randint(snake_size, screen_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_UP:
snake_direction = UP
elif event.key == pygame.K_DOWN:
snake_direction = DOWN
elif event.key == pygame.K_LEFT:
snake_direction = LEFT
elif event.key == pygame.K_RIGHT:
snake_direction = RIGHT
# 移动蛇的头部
if snake_direction == UP:
snake_y -= snake_size
elif snake_direction == DOWN:
snake_y += snake_size
elif snake_direction == LEFT:
snake_x -= snake_size
elif snake_direction == RIGHT:
snake_x += snake_size
# 判断蛇是否撞墙
if snake_x < 0 or snake_x > screen_width - snake_size or snake_y < 0 or snake_y > screen_height - snake_size:
game_over = True
# 判断蛇是否吃到食物
if abs(snake_x - food_x) < snake_size and abs(snake_y - food_y) < snake_size:
snake_length += 1
food_x = random.randint(snake_size, screen_width - food_size)
food_y = random.randint(snake_size, screen_height - food_size)
# 更新蛇的身体
snake_body.insert(0, (snake_x, snake_y))
if len(snake_body) > snake_length:
snake_body.pop()
# 绘制游戏界面
screen.fill((0, 0, 0))
pygame.draw.rect(screen, food_color, (food_x, food_y, food_size, food_size))
for body_part in snake_body:
pygame.draw.rect(screen, snake_color, (body_part[0], body_part[1], snake_size, snake_size))
pygame.display.update()
# 控制游戏帧率
clock.tick(fps)
# 退出 Pygame
pygame.quit()
```
这个代码实现了一个比较简单的贪吃蛇游戏,玩家通过方向键控制蛇的移动,蛇吃到食物后会变长,撞墙或者咬到自己就会游戏结束。
阅读全文