使用python写一个贪吃蛇的游戏
时间: 2024-12-10 12:43:10 浏览: 18
编写一个简单的Python贪吃蛇游戏通常会涉及基本的图形用户界面、游戏循环、键盘事件处理以及蛇的移动和食物生成等核心功能。下面是一个简化的示例,我们将使用pygame库来创建这个游戏:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
window_size = (400, 400)
screen = pygame.display.set_mode(window_size)
# 定义颜色
snake_color = (0, 255, 0)
food_color = (255, 0, 0)
# 创建初始蛇的位置和长度
snake = [[100, 100], [90, 100], [80, 100]]
snake_direction = "right"
# 食物位置
food = [random.randint(0, window_size[0] - 20), random.randint(0, window_size[1] - 20)]
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
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"
# 移动蛇并检测边界
new_head = [snake[-1][0], snake[-1][1]]
if snake_direction == "up":
new_head[1] -= 10
elif snake_direction == "down":
new_head[1] += 10
elif snake_direction == "left":
new_head[0] -= 10
elif snake_direction == "right":
new_head[0] += 10
if new_head in snake[:-1]:
print("Game Over!")
break
snake.insert(0, new_head)
# 检查蛇是否吃到食物
if snake[0] == food:
food = [random.randint(0, window_size[0] - 20), random.randint(0, window_size[1] - 20)]
snake.append([snake[-1][0], snake[-1][1]])
else:
tail = snake.pop()
# 绘制游戏元素
screen.fill((0, 0, 0))
for pos in snake:
pygame.draw.rect(screen, snake_color, [pos[0], pos[1], 20, 20])
pygame.draw.rect(screen, food_color, [food[0], food[1], 20, 20])
# 更新屏幕
pygame.display.update()
# 结束游戏
pygame.quit()
```
这个游戏非常基础,玩家通过方向键控制蛇的移动,吃到食物则蛇变长,撞到墙或自身则游戏结束。你可以在此基础上添加更复杂的功能,比如碰撞检测、得分系统等。
阅读全文