你能用pthon写一个贪吃蛇吗
时间: 2024-01-06 13:04:42 浏览: 81
当然可以!以下是一个简单的贪吃蛇游戏的示例代码:
```python
import pygame
import random
# 游戏窗口的大小
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
GRID_SIZE = 20
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 蛇的初始位置和长度
snake_positions = [(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)]
snake_length = 1
# 蛇的移动方向
snake_direction = "right"
# 食物的初始位置
food_position = (random.randint(0, WINDOW_WIDTH / GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, WINDOW_HEIGHT / GRID_SIZE - 1) * GRID_SIZE)
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
window.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 检测按键事件
if 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_head = list(snake_positions[0])
if snake_direction == "up":
snake_head[1] -= GRID_SIZE
elif snake_direction == "down":
snake_head[1] += GRID_SIZE
elif snake_direction == "left":
snake_head[0] -= GRID_SIZE
elif snake_direction == "right":
snake_head[0] += GRID_SIZE
# 检测蛇是否吃到食物
if tuple(snake_head) == food_position:
food_position = (random.randint(0, WINDOW_WIDTH / GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, WINDOW_HEIGHT / GRID_SIZE - 1) * GRID_SIZE)
snake_length += 1
else:
# 如果没有吃到食物,去掉蛇尾
snake_positions.pop()
# 检测蛇是否碰到墙壁或自己的身体
if (snake_head[0] < 0 or snake_head[0] >= WINDOW_WIDTH or
snake_head[1] < 0 or snake_head[1] >= WINDOW_HEIGHT or
tuple(snake_head) in snake_positions):
running = False
# 更新蛇的位置
snake_positions.insert(0, tuple(snake_head))
# 绘制蛇和食物
for position in snake_positions:
pygame.draw.rect(window, GREEN, (position[0], position[1], GRID_SIZE, GRID_SIZE))
pygame.draw.rect(window, RED, (food_position[0], food_position[1], GRID_SIZE, GRID_SIZE))
# 更新窗口显示
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 退出游戏
pygame.quit()
```
这是一个基本的贪吃蛇游戏,使用了pygame库来实现窗口和图形的绘制,通过键盘事件来控制蛇的移动方向,检测碰撞等逻辑。你可以在此基础上进行更多的扩展和优化。希望对你有帮助!
阅读全文