帮我用python写一个贪吃蛇的游戏
时间: 2024-05-29 17:04:10 浏览: 85
好的,这个问题是关于编程的,我可以为您提供帮助。
以下是一个简单的Python贪吃蛇游戏示例代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
window_size = window_width, window_height = 400, 400
window_title = "贪吃蛇"
window = pygame.display.set_mode(window_size)
pygame.display.set_caption(window_title)
# 设置FPS
clock = pygame.time.Clock()
fps = 30
# 定义贪吃蛇和食物的坐标和大小
snake_size = (10, 10)
snake_pos = [window_width / 2, window_height / 2]
snake_speed = 10
snake_direction = "UP"
food_size = (10, 10)
food_pos = [random.randrange(0, window_width, 10), random.randrange(0, window_height, 10)]
# 定义游戏循环
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_direction = "UP"
elif event.key == pygame.K_DOWN:
snake_direction = "DOWN"
elif event.key == pygame.K_LEFT:
snake_direction = "LEFT"
elif event.key == pygame.K_RIGHT:
snake_direction = "RIGHT"
# 移动贪吃蛇
if snake_direction == "UP":
snake_pos[1] -= snake_speed
elif snake_direction == "DOWN":
snake_pos[1] += snake_speed
elif snake_direction == "LEFT":
snake_pos[0] -= snake_speed
elif snake_direction == "RIGHT":
snake_pos[0] += snake_speed
# 检查贪吃蛇是否与边界相撞
if snake_pos[0] < 0 or snake_pos[0] > window_width - snake_size[0] or snake_pos[1] < 0 or snake_pos[1] > window_height - snake_size[1]:
running = False
# 检查贪吃蛇是否吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randrange(0, window_width, 10), random.randrange(0, window_height, 10)]
# 绘制游戏界面
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 255, 0), (snake_pos[0], snake_pos[1], snake_size[0], snake_size[1]))
pygame.draw.rect(window, (255, 0, 0), (food_pos[0], food_pos[1], food_size[0], food_size[1]))
pygame.display.update()
# 设置帧率
clock.tick(fps)
# 退出pygame
pygame.quit()
```
在运行这段代码时,会自动打开一个窗口,您可以通过按上下左右键控制贪吃蛇的方向,以吃到食物。当贪吃蛇与边界相撞或者按下关闭窗口时,游戏结束。
阅读全文