写一个贪吃蛇代码
时间: 2024-02-16 08:03:21 浏览: 29
以下是一个简单的 Python 贪吃蛇代码实现,供参考:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
window_width = 500
window_height = 500
game_window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义常量
cell_size = 10
directions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
# 定义贪吃蛇和食物的类
class Snake:
def __init__(self):
self.cells = [(100, 100), (90, 100), (80, 100)]
self.direction = 'RIGHT'
def draw(self):
for cell in self.cells:
pygame.draw.rect(game_window, white, (cell[0], cell[1], cell_size, cell_size))
def move(self):
head = self.cells[0]
dx, dy = 0, 0
if self.direction == 'RIGHT':
dx = cell_size
elif self.direction == 'LEFT':
dx = -cell_size
elif self.direction == 'UP':
dy = -cell_size
elif self.direction == 'DOWN':
dy = cell_size
new_head = (head[0] + dx, head[1] + dy)
self.cells.insert(0, new_head)
self.cells.pop()
def change_direction(self, new_direction):
if new_direction in directions and new_direction != self.direction:
self.direction = new_direction
def check_collision(self):
head = self.cells[0]
if head[0] < 0 or head[0] >= window_width or head[1] < 0 or head[1] >= window_height:
return True
for cell in self.cells[1:]:
if head == cell:
return True
return False
def eat_food(self, food):
if self.cells[0] == food.position:
self.cells.append(self.cells[-1])
return True
return False
class Food:
def __init__(self):
self.position = (random.randint(0, window_width - cell_size), random.randint(0, window_height - cell_size))
def draw(self):
pygame.draw.rect(game_window, red, (self.position[0], self.position[1], cell_size, cell_size))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
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:
snake.change_direction('UP')
elif event.key == pygame.K_DOWN:
snake.change_direction('DOWN')
elif event.key == pygame.K_LEFT:
snake.change_direction('LEFT')
elif event.key == pygame.K_RIGHT:
snake.change_direction('RIGHT')
# 移动贪吃蛇
snake.move()
# 检查碰撞
if snake.check_collision():
game_over = True
# 检查吃食物
if snake.eat_food(food):
food = Food()
# 渲染游戏窗口
game_window.fill(black)
snake.draw()
food.draw()
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 退出 Pygame
pygame.quit()
```
这段代码实现了一个基本的贪吃蛇游戏,包括贪吃蛇的移动、改变方向、检查碰撞、吃食物等功能。可以通过修改常量和调整参数来调整游戏的难度和表现。