能不能用python写个贪吃蛇游戏,请给出程序
时间: 2024-05-08 21:18:13 浏览: 9
当然可以!下面是一个简单的Python贪吃蛇游戏程序:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 设置游戏窗口尺寸
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 创建游戏窗口
WINDOW_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇游戏')
# 设置帧率
FPS = 10
clock = pygame.time.Clock()
# 定义方格大小和蛇的初始位置和移动速度
SIZE = 20
SNAKE_POSITION = [(3 * SIZE, 0), (2 * SIZE, 0), (SIZE, 0)]
SPEED = (SIZE, 0)
# 定义食物的初始位置
FOOD_POSITION = (int(random.randint(0, WINDOW_WIDTH - SIZE) / SIZE) * SIZE,
int(random.randint(0, WINDOW_HEIGHT - SIZE) / SIZE) * SIZE)
# 循环控制变量
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
# 改变蛇的移动速度
if event.key == pygame.K_LEFT and SPEED != (SIZE, 0):
SPEED = (-SIZE, 0)
elif event.key == pygame.K_RIGHT and SPEED != (-SIZE, 0):
SPEED = (SIZE, 0)
elif event.key == pygame.K_UP and SPEED != (0, SIZE):
SPEED = (0, -SIZE)
elif event.key == pygame.K_DOWN and SPEED != (0, -SIZE):
SPEED = (0, SIZE)
# 移动蛇
SNAKE_POSITION.insert(0, (SNAKE_POSITION[0][0] + SPEED[0], SNAKE_POSITION[0][1] + SPEED[1]))
if SNAKE_POSITION[0] == FOOD_POSITION:
# 吃掉食物,重新生成食物
FOOD_POSITION = (int(random.randint(0, WINDOW_WIDTH - SIZE) / SIZE) * SIZE,
int(random.randint(0, WINDOW_HEIGHT - SIZE) / SIZE) * SIZE)
else:
# 没有吃到食物,将蛇的尾部去掉
SNAKE_POSITION.pop()
# 检测蛇是否撞到自己或撞墙
if SNAKE_POSITION[0] in SNAKE_POSITION[1:] \
or SNAKE_POSITION[0][0] < 0 or SNAKE_POSITION[0][0] >= WINDOW_WIDTH \
or SNAKE_POSITION[0][1] < 0 or SNAKE_POSITION[0][1] >= WINDOW_HEIGHT:
game_over = True
# 绘制游戏窗口
WINDOW_SURFACE.fill(WHITE)
pygame.draw.rect(WINDOW_SURFACE, RED, pygame.Rect(FOOD_POSITION[0], FOOD_POSITION[1], SIZE, SIZE))
for position in SNAKE_POSITION:
pygame.draw.rect(WINDOW_SURFACE, BLACK, pygame.Rect(position[0], position[1], SIZE, SIZE))
pygame.display.update()
# 控制帧率
clock.tick(FPS)
# 退出pygame
pygame.quit()
```
希望这个程序对你有所帮助!