写一个贪吃蛇程序,python
时间: 2024-02-01 22:14:50 浏览: 61
基于python的贪吃蛇程序
好的,下面是一个简单的贪吃蛇程序,使用Python和Pygame库编写:
```python
import pygame
import random
# 初始化Pygame模块
pygame.init()
# 定义游戏窗口大小和游戏区域大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
CELL_SIZE = 25
GAME_AREA_WIDTH = WINDOW_WIDTH - CELL_SIZE * 2
GAME_AREA_HEIGHT = WINDOW_HEIGHT - CELL_SIZE * 2
# 定义游戏区域的边界
LEFT_BOUNDARY = CELL_SIZE
RIGHT_BOUNDARY = WINDOW_WIDTH - CELL_SIZE
TOP_BOUNDARY = CELL_SIZE
BOTTOM_BOUNDARY = WINDOW_HEIGHT - CELL_SIZE
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 创建时钟对象,用于控制游戏帧率
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.body = [(GAME_AREA_WIDTH // 2, GAME_AREA_HEIGHT // 2)]
self.direction = 'right'
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= CELL_SIZE
elif self.direction == 'down':
y += CELL_SIZE
elif self.direction == 'left':
x -= CELL_SIZE
elif self.direction == 'right':
x += CELL_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def grow(self):
x, y = self.body[0]
if self.direction == 'up':
y -= CELL_SIZE
elif self.direction == 'down':
y += CELL_SIZE
elif self.direction == 'left':
x -= CELL_SIZE
elif self.direction == 'right':
x += CELL_SIZE
self.body.insert(0, (x, y))
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, WHITE, (x, y, CELL_SIZE, CELL_SIZE))
class Food:
def __init__(self):
self.x = random.randint(LEFT_BOUNDARY // CELL_SIZE + 1, RIGHT_BOUNDARY // CELL_SIZE - 1) * CELL_SIZE
self.y = random.randint(TOP_BOUNDARY // CELL_SIZE + 1, BOTTOM_BOUNDARY // CELL_SIZE - 1) * CELL_SIZE
def draw(self):
pygame.draw.circle(window, RED, (self.x + CELL_SIZE // 2, self.y + CELL_SIZE // 2), CELL_SIZE // 2)
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏主循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
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()
food = Food()
# 判断是否撞到边界或自己的身体
if snake.body[0][0] < LEFT_BOUNDARY or snake.body[0][0] >= RIGHT_BOUNDARY or \
snake.body[0][1] < TOP_BOUNDARY or snake.body[0][1] >= BOTTOM_BOUNDARY or \
snake.body[0] in snake.body[1:]:
print('游戏结束!')
pygame.quit()
exit()
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.draw.rect(window, WHITE, (LEFT_BOUNDARY, TOP_BOUNDARY, GAME_AREA_WIDTH, GAME_AREA_HEIGHT), 1)
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
```
运行程序后,会弹出一个窗口,按照方向键控制贪吃蛇的移动。吃到食物会增加蛇身的长度,撞到边界或自己的身体则游戏结束。
阅读全文