python做一个贪吃蛇
时间: 2023-10-06 12:07:06 浏览: 81
python做的贪吃蛇
好的,下面是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 定义窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 定义贪吃蛇的大小
SNAKE_SIZE = 20
# 定义食物的大小
FOOD_SIZE = 20
# 定义贪吃蛇移动的速度
SPEED = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置窗口标题
pygame.display.set_caption("贪吃蛇")
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = 'right'
def move(self):
# 获取贪吃蛇头部的坐标
x, y = self.body[0]
if self.direction == 'up':
y -= SNAKE_SIZE
elif self.direction == 'down':
y += SNAKE_SIZE
elif self.direction == 'left':
x -= SNAKE_SIZE
elif self.direction == 'right':
x += SNAKE_SIZE
# 将新的头部坐标插入到body列表中的第一个位置
self.body.insert(0, (x, y))
# 删除body列表中的最后一个坐标
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, SNAKE_SIZE, SNAKE_SIZE))
def eat(self, food):
x1, y1 = self.body[0]
x2, y2 = food
if x1 == x2 and y1 == y2:
# 如果贪吃蛇吃到了食物,就将食物添加到body列表的头部
self.body.insert(0, food)
return True
else:
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
self.y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, FOOD_SIZE, FOOD_SIZE))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 如果点击了窗口的关闭按钮,则退出游戏
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
# 处理键盘事件
if 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'
elif 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'
# 移动贪吃蛇
snake.move()
# 判断贪吃蛇是否吃到了食物
if snake.eat((food.x, food.y)):
# 如果贪吃蛇吃到了食物,则重新生成食物
food = Food()
# 绘制游戏界面
screen.fill(WHITE)
snake.draw()
food.draw()
pygame.display.update()
# 判断贪吃蛇是否碰到了边界或者自己的身体
x, y = snake.body[0]
if x < 0 or x + SNAKE_SIZE > WINDOW_WIDTH or y < 0 or y + SNAKE_SIZE > WINDOW_HEIGHT:
print("Game Over!")
pygame.quit()
exit()
for i in range(1, len(snake.body)):
if snake.body[i] == snake.body[0]:
print("Game Over!")
pygame.quit()
exit()
# 控制游戏速度
pygame.time.Clock().tick(SPEED)
```
运行上述代码即可在pygame窗口中看到贪吃蛇游戏。
阅读全文