写一个python贪吃蛇
时间: 2023-07-01 19:19:14 浏览: 172
如何用Python写一个贪吃蛇AI.docx
好的,以下是一个简单的Python贪吃蛇游戏。
```python
import pygame
import random
# 定义一些常量
WIDTH = 800
HEIGHT = 600
FPS = 10
BLOCK_SIZE = 20
# 定义一些颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化 Pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
# 定义一些函数
def draw_block(color, x, y):
pygame.draw.rect(screen, color, [x, y, BLOCK_SIZE, BLOCK_SIZE])
def game_over():
font = pygame.font.SysFont(None, 48)
text = font.render("游戏结束", True, WHITE)
screen.blit(text, (WIDTH / 2 - text.get_width() / 2, HEIGHT / 2 - text.get_height() / 2))
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
quit()
# 定义 Snake 类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(WIDTH / 2, HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x * BLOCK_SIZE)), (cur[1] + (y * BLOCK_SIZE)))
if new in self.positions[2:]:
game_over()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def draw(self):
for p in self.positions:
draw_block(self.color, p[0], p[1])
# 定义 Food 类
class Food:
def __init__(self):
x = random.randrange(0, WIDTH, BLOCK_SIZE)
y = random.randrange(0, HEIGHT, BLOCK_SIZE)
self.position = (x, y)
self.color = RED
def draw(self):
draw_block(self.color, self.position[0], self.position[1])
# 定义一些方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 创建 Snake 和 Food 对象
snake = Snake()
food = Food()
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.turn(UP)
elif event.key == pygame.K_DOWN:
snake.turn(DOWN)
elif event.key == pygame.K_LEFT:
snake.turn(LEFT)
elif event.key == pygame.K_RIGHT:
snake.turn(RIGHT)
# 移动 Snake
snake.move()
# 检查是否碰到了 Food
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
# 绘制背景
screen.fill(BLACK)
# 绘制 Snake 和 Food
snake.draw()
food.draw()
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(FPS)
# 退出 Pygame
pygame.quit()
```
希望这个简单的贪吃蛇游戏可以帮到你。
阅读全文