用python写一个贪吃蛇游戏
时间: 2024-05-06 07:17:39 浏览: 59
好的,下面是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame, random
# 初始化pygame模块
pygame.init()
# 设置窗口大小和标题
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置字体
font = pygame.font.SysFont(None, 30)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.size = 20
self.x = [random.randint(0, width - self.size) // self.size * self.size]
self.y = [random.randint(0, height - self.size) // self.size * self.size]
self.direction = random.choice(['left', 'right', 'up', 'down'])
def move(self):
if self.direction == 'left':
self.x[0] -= self.size
elif self.direction == 'right':
self.x[0] += self.size
elif self.direction == 'up':
self.y[0] -= self.size
elif self.direction == 'down':
self.y[0] += self.size
# 判断是否撞墙
if self.x[0] < 0 or self.x[0] > width - self.size or self.y[0] < 0 or self.y[0] > height - self.size:
return True
# 判断是否吃到食物
if self.x[0] == food.x and self.y[0] == food.y:
self.x.append(self.x[-1])
self.y.append(self.y[-1])
food.generate()
# 判断是否撞到自己
for i in range(1, len(self.x)):
if self.x[i] == self.x[0] and self.y[i] == self.y[0]:
return True
# 移动身体
for i in range(len(self.x) - 1, 0, -1):
self.x[i] = self.x[i - 1]
self.y[i] = self.y[i - 1]
return False
def draw(self):
for i in range(len(self.x)):
pygame.draw.rect(screen, green, (self.x[i], self.y[i], self.size, self.size))
# 定义食物类
class Food:
def __init__(self):
self.size = 20
self.generate()
def generate(self):
self.x = random.randint(0, width - self.size) // self.size * self.size
self.y = random.randint(0, height - self.size) // self.size * self.size
def draw(self):
pygame.draw.rect(screen, red, (self.x, self.y, self.size, self.size))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
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_LEFT and snake.direction != 'right':
snake.direction = 'left'
elif event.key == pygame.K_RIGHT and snake.direction != 'left':
snake.direction = 'right'
elif 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'
# 移动贪吃蛇
if snake.move():
break
# 刷新屏幕
screen.fill(white)
snake.draw()
food.draw()
pygame.display.update()
# 设置帧率
pygame.time.Clock().tick(10)
# 显示游戏结束的信息
text = font.render('游戏结束!', True, black)
screen.blit(text, (width // 2 - text.get_width() // 2, height // 2 - text.get_height() // 2))
pygame.display.update()
# 等待3秒后退出程序
pygame.time.wait(3000)
pygame.quit()
quit()
```
运行以上代码,即可开始玩贪吃蛇游戏。
阅读全文