使用python3 编写一个贪吃蛇游戏,给我完整的代码
时间: 2024-02-13 07:05:53 浏览: 79
python贪吃蛇游戏
好的,以下是使用Python3编写的贪吃蛇游戏的完整代码。代码注释中有详细的说明。
```python
import pygame
import random
# 游戏界面大小和每个方块的大小
WIDTH, HEIGHT = 640, 480
GRID_SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
class Snake:
def __init__(self):
# 初始化蛇的位置
self.body = [(WIDTH/2, HEIGHT/2), (WIDTH/2-GRID_SIZE, HEIGHT/2), (WIDTH/2-2*GRID_SIZE, HEIGHT/2)]
# 初始化蛇的移动方向
self.direction = "right"
# 初始化蛇是否死亡
self.is_dead = False
def move(self):
# 蛇移动
head = self.body[0]
if self.direction == "right":
new_head = (head[0]+GRID_SIZE, head[1])
elif self.direction == "left":
new_head = (head[0]-GRID_SIZE, head[1])
elif self.direction == "up":
new_head = (head[0], head[1]-GRID_SIZE)
elif self.direction == "down":
new_head = (head[0], head[1]+GRID_SIZE)
# 判断蛇移动后是否死亡
if new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT:
self.is_dead = True
elif new_head in self.body:
self.is_dead = True
# 移动蛇
if not self.is_dead:
self.body.insert(0, new_head)
if new_head != self.food:
self.body.pop()
else:
self.add_food()
def add_food(self):
# 随机生成食物的位置
while True:
x = random.randint(0, WIDTH/GRID_SIZE-1) * GRID_SIZE
y = random.randint(0, HEIGHT/GRID_SIZE-1) * GRID_SIZE
if (x, y) not in self.body:
break
self.food = (x, y)
def draw(self, surface):
# 画出蛇和食物
for block in self.body:
pygame.draw.rect(surface, GREEN, (block[0], block[1], GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, RED, (self.food[0], self.food[1], GRID_SIZE, GRID_SIZE))
class Game:
def __init__(self):
# 初始化游戏界面
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# 初始化蛇和食物
self.snake = Snake()
self.snake.add_food()
# 初始化计时器
self.clock = pygame.time.Clock()
def run(self):
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and self.snake.direction != "left":
self.snake.direction = "right"
elif event.key == pygame.K_LEFT and self.snake.direction != "right":
self.snake.direction = "left"
elif event.key == pygame.K_UP and self.snake.direction != "down":
self.snake.direction = "up"
elif event.key == pygame.K_DOWN and self.snake.direction != "up":
self.snake.direction = "down"
# 移动蛇
self.snake.move()
# 画出蛇和食物
self.screen.fill(BLACK)
self.snake.draw(self.screen)
# 判断游戏是否结束
if self.snake.is_dead:
font = pygame.font.Font(None, 36)
text = font.render("Game Over", True, WHITE)
self.screen.blit(text, (WIDTH/2-70, HEIGHT/2-18))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
quit()
# 刷新屏幕
pygame.display.update()
# 控制游戏帧率
self.clock.tick(10)
if __name__ == "__main__":
pygame.init()
game = Game()
game.run()
```
阅读全文