写一个python 贪吃蛇游戏代码
时间: 2024-02-01 14:02:02 浏览: 114
好的,以下是一个简单的 Python 贪吃蛇游戏代码,注释已经尽可能详细,希望能帮到你:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏区域的宽度和高度
WIDTH, HEIGHT = 640, 480
# 食物的大小
FOOD_SIZE = 16
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 加载字体
font = pygame.font.SysFont("Arial", 24)
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义蛇的类
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.size = 16
self.speed = 16
self.direction = "right"
self.body = [{"x": x, "y": y}]
def draw(self):
for part in self.body:
pygame.draw.rect(screen, GREEN, (part["x"], part["y"], self.size, self.size))
def move(self):
if self.direction == "right":
self.x += self.speed
elif self.direction == "left":
self.x -= self.speed
elif self.direction == "up":
self.y -= self.speed
elif self.direction == "down":
self.y += self.speed
# 在蛇头的位置插入新的身体
self.body.insert(0, {"x": self.x, "y": self.y})
# 删除最后一节身体
self.body.pop()
def eat_food(self, food):
if self.x == food.x and self.y == food.y:
self.body.append({"x": self.x, "y": self.y})
return True
else:
return False
def check_collision(self):
# 检测是否撞墙
if self.x < 0 or self.x > WIDTH - self.size or self.y < 0 or self.y > HEIGHT - self.size:
return True
# 检测是否撞到自己的身体
for part in self.body[1:]:
if self.x == part["x"] and self.y == part["y"]:
return True
return False
# 定义食物的类
class Food:
def __init__(self):
self.x = random.randint(0, WIDTH - FOOD_SIZE)
self.y = random.randint(0, HEIGHT - FOOD_SIZE)
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, FOOD_SIZE, FOOD_SIZE))
# 创建蛇和食物
snake = Snake(WIDTH / 2, HEIGHT / 2)
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = "right"
elif event.key == pygame.K_LEFT:
snake.direction = "left"
elif event.key == pygame.K_UP:
snake.direction = "up"
elif event.key == pygame.K_DOWN:
snake.direction = "down"
# 移动蛇
snake.move()
# 检测是否吃到食物
if snake.eat_food(food):
food = Food()
# 绘制游戏界面
screen.fill(BLACK)
snake.draw()
food.draw()
# 检测游戏是否结束
if snake.check_collision():
text = font.render("游戏结束!", True, WHITE)
screen.blit(text, (WIDTH / 2 - text.get_width() / 2, HEIGHT / 2 - text.get_height() / 2))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
exit()
# 更新屏幕
pygame.display.update()
pygame.time.Clock().tick(10)
```
运行该代码后,你就可以玩一下简单的贪吃蛇游戏了。希望对你有所帮助!
阅读全文