使用python写一个贪吃蛇游戏
时间: 2024-02-02 13:03:12 浏览: 86
Python编写一个贪吃蛇游戏
好的,下面是一个简单的贪吃蛇游戏代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
# 设置窗口大小
size = (500, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("贪吃蛇游戏")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.snake_list = [(250, 250), (240, 250), (230, 250)]
self.direction = "right"
def move(self):
if self.direction == "right":
head = (self.snake_list[0][0]+10, self.snake_list[0][1])
elif self.direction == "left":
head = (self.snake_list[0][0]-10, self.snake_list[0][1])
elif self.direction == "up":
head = (self.snake_list[0][0], self.snake_list[0][1]-10)
elif self.direction == "down":
head = (self.snake_list[0][0], self.snake_list[0][1]+10)
self.snake_list.insert(0, head)
self.snake_list.pop(-1)
def change_direction(self, direction):
if direction == "right" and self.direction != "left":
self.direction = "right"
elif direction == "left" and self.direction != "right":
self.direction = "left"
elif direction == "up" and self.direction != "down":
self.direction = "up"
elif direction == "down" and self.direction != "up":
self.direction = "down"
# 定义食物类
class Food:
def __init__(self):
self.position = (random.randint(0, 49)*10, random.randint(0, 49)*10)
def generate(self):
self.position = (random.randint(0, 49)*10, random.randint(0, 49)*10)
# 创建贪吃蛇和食物对象
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
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.change_direction("right")
elif event.key == pygame.K_LEFT:
snake.change_direction("left")
elif event.key == pygame.K_UP:
snake.change_direction("up")
elif event.key == pygame.K_DOWN:
snake.change_direction("down")
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.snake_list[0] == food.position:
food.generate()
snake.snake_list.append(snake.snake_list[-1])
# 判断是否游戏结束
if snake.snake_list[0][0] < 0 or snake.snake_list[0][0] >= 500 or snake.snake_list[0][1] < 0 or snake.snake_list[0][1] >= 500:
game_over = True
for i in range(1, len(snake.snake_list)):
if snake.snake_list[0] == snake.snake_list[i]:
game_over = True
# 绘制游戏画面
screen.fill(white)
for pos in snake.snake_list:
pygame.draw.rect(screen, green, [pos[0], pos[1], 10, 10])
pygame.draw.rect(screen, red, [food.position[0], food.position[1], 10, 10])
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 退出pygame
pygame.quit()
```
运行这段代码,即可看到一个简单的贪吃蛇游戏窗口。使用方向键控制贪吃蛇的移动,尽可能吃到食物,避免碰到墙壁或自己的身体。
阅读全文