用python写一个简单的贪吃蛇游戏
时间: 2023-07-04 16:21:04 浏览: 91
Python编写一个贪吃蛇游戏
好的,这里提供一个基于 Python3 和 Pygame 的简单贪吃蛇游戏代码:
```python
import pygame
import random
# 定义一些常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
BLOCK_SIZE = 20
SNAKE_INIT_POS = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)]
FONT_SIZE = 24
FONT_COLOR = (255, 255, 255)
# 初始化 Pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义字体
font = pygame.font.SysFont(None, FONT_SIZE)
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义游戏对象
class Snake:
def __init__(self):
self.body = SNAKE_INIT_POS[:]
self.direction = "right"
self.grow = False
def move(self):
# 计算新的蛇头位置
x, y = self.body[0]
if self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "right":
x += BLOCK_SIZE
# 插入新的蛇头
self.body.insert(0, (x, y))
# 如果不需要增长,删除最后一个方块
if not self.grow:
self.body.pop()
else:
self.grow = False
def grow_snake(self):
self.grow = True
def is_collided(self, x, y):
# 判断蛇是否碰到了自己
for block in self.body[1:]:
if block == (x, y):
return True
# 判断蛇是否碰到了边界
if x < 0 or x >= SCREEN_WIDTH or y < 0 or y >= SCREEN_HEIGHT:
return True
return False
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, green, (x, y, BLOCK_SIZE, BLOCK_SIZE))
class Food:
def __init__(self):
self.x, self.y = self.generate_new_pos()
def generate_new_pos(self):
x = random.randint(0, SCREEN_WIDTH // BLOCK_SIZE - 1) * BLOCK_SIZE
y = random.randint(0, SCREEN_HEIGHT // BLOCK_SIZE - 1) * BLOCK_SIZE
return x, y
def draw(self):
pygame.draw.rect(screen, red, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
# 初始化游戏对象
snake = Snake()
food = Food()
# 游戏循环
clock = pygame.time.Clock()
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_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.body[0] == (food.x, food.y):
snake.grow_snake()
food.x, food.y = food.generate_new_pos()
# 判断是否游戏结束
if snake.is_collided(snake.body[0][0], snake.body[0][1]):
screen.fill(black)
text = font.render("Game Over!", True, FONT_COLOR)
text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
screen.blit(text, text_rect)
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
quit()
# 绘制游戏对象
screen.fill(black)
snake.draw()
food.draw()
pygame.display.update()
# 控制帧率
clock.tick(10)
```
这个贪吃蛇游戏使用 Pygame 库来实现,可以在终端或者 Pycharm 等 Python 开发环境中运行。通过按键来控制蛇的方向,蛇碰到边界或者自己时游戏结束。
阅读全文