写一个贪吃蛇python并写上注释
时间: 2024-01-06 14:05:03 浏览: 73
python编写的贪吃蛇
5星 · 资源好评率100%
好的,以下是一个简单的贪吃蛇游戏的Python代码及注释:
```python
import pygame
import random
# 初始化Pygame库
pygame.init()
# 游戏窗口的大小和标题
window_width = 600
window_height = 400
window_title = "贪吃蛇游戏"
# 定义一些颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption(window_title)
# 定义蛇的初始位置和大小
snake_x = window_width / 2
snake_y = window_height / 2
snake_size = 10
# 定义蛇的移动速度
snake_speed = 10
# 定义蛇的初始方向
snake_direction = "right"
# 定义食物的初始位置和大小
food_x = random.randint(0, window_width - snake_size)
food_y = random.randint(0, window_height - snake_size)
food_size = 10
# 定义游戏结束标志
game_over = False
# 定义游戏时钟
clock = pygame.time.Clock()
# 游戏循环
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 + food_size and snake_x + snake_size > food_x and snake_y < food_y + food_size and snake_y + snake_size > food_y:
# 如果吃到了,重新生成食物的位置
food_x = random.randint(0, window_width - snake_size)
food_y = random.randint(0, window_height - snake_size)
# 绘制游戏窗口
window.fill(black)
pygame.draw.rect(window, green, [food_x, food_y, food_size, food_size])
pygame.draw.rect(window, blue, [snake_x, snake_y, snake_size, snake_size])
pygame.display.update()
# 判断游戏是否结束
if snake_x < 0 or snake_x + snake_size > window_width or snake_y < 0 or snake_y + snake_size > window_height:
game_over = True
# 控制游戏的速度
clock.tick(30)
# 退出Pygame库
pygame.quit()
```
注释已经在代码中给出,希望对您有所帮助!
阅读全文