给我写一个贪吃蛇代码,代码里面有详细的注释
时间: 2023-06-16 19:03:24 浏览: 94
好的,以下是一个简单的贪吃蛇代码,带有详细的注释:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
WINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)
# 设置游戏窗口标题
pygame.display.set_caption('Snake Game')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建游戏窗口
screen = pygame.display.set_mode(WINDOW_SIZE)
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置游戏变量
score = 0 # 得分
game_over = False # 游戏结束标志
# 定义方向常量
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.x = 0 # 贪吃蛇头部x坐标
self.y = 0 # 贪吃蛇头部y坐标
self.direction = RIGHT # 贪吃蛇初始方向
self.body = [] # 贪吃蛇身体列表
self.length = 3 # 贪吃蛇初始长度
def move(self):
# 根据方向移动贪吃蛇
if self.direction == UP:
self.y -= 20
elif self.direction == DOWN:
self.y += 20
elif self.direction == LEFT:
self.x -= 20
elif self.direction == RIGHT:
self.x += 20
# 将新的头部坐标加入贪吃蛇身体列表
self.body.insert(0, (self.x, self.y))
# 如果贪吃蛇的长度大于指定长度,则删除尾部坐标
if len(self.body) > self.length:
self.body.pop()
def draw(self):
# 绘制贪吃蛇
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, 20, 20))
def collision(self):
# 判断贪吃蛇是否与边界或自身碰撞
if self.x < 0 or self.x > WINDOW_WIDTH - 20 or self.y < 0 or self.y > WINDOW_HEIGHT - 20:
return True
for x, y in self.body[1:]:
if self.x == x and self.y == y:
return True
return False
def eat(self, food):
# 判断贪吃蛇是否吃到食物
if self.x == food.x and self.y == food.y:
self.length += 1 # 贪吃蛇长度加1
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randrange(0, WINDOW_WIDTH - 20, 20) # 食物x坐标
self.y = random.randrange(0, WINDOW_HEIGHT - 20, 20) # 食物y坐标
def draw(self):
# 绘制食物
pygame.draw.rect(screen, RED, (self.x, self.y, 20, 20))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
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 and snake.direction != DOWN:
snake.direction = UP
elif event.key == pygame.K_DOWN and snake.direction != UP:
snake.direction = DOWN
elif 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
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.eat(food):
# 创建新的食物对象
food = Food()
# 得分加1
score += 1
# 绘制背景
screen.fill(BLACK)
# 绘制得分文本
font = pygame.font.SysFont(None, 30)
text = font.render('Score: ' + str(score), True, WHITE)
screen.blit(text, (10, 10))
# 绘制贪吃蛇和食物
snake.draw()
food.draw()
# 判断是否与边界或自身碰撞
if snake.collision():
game_over = True
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
clock.tick(10)
# 退出pygame
pygame.quit()
```
希望对你有帮助!
阅读全文