能用python写一个贪吃蛇游戏吗
时间: 2023-07-20 11:16:32 浏览: 54
Python编写一个贪吃蛇游戏
当然可以!以下是一个简单的贪吃蛇游戏的Python代码示例:
```python
import pygame
import random
# 初始化
pygame.init()
# 屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 蛇的初始位置和大小
snake_pos = [[250, 250], [240, 250], [230, 250], [220, 250]]
snake_size = 10
# 食物的初始位置和大小
food_pos = [random.randrange(1, SCREEN_WIDTH // 10) * 10, random.randrange(1, SCREEN_HEIGHT // 10) * 10]
food_size = 10
# 蛇的移动方向
direction = "RIGHT"
# 控制游戏循环的变量
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:
direction = "LEFT"
elif event.key == pygame.K_RIGHT:
direction = "RIGHT"
elif event.key == pygame.K_UP:
direction = "UP"
elif event.key == pygame.K_DOWN:
direction = "DOWN"
# 移动蛇头
if direction == "LEFT":
head = [snake_pos[0][0] - snake_size, snake_pos[0][1]]
elif direction == "RIGHT":
head = [snake_pos[0][0] + snake_size, snake_pos[0][1]]
elif direction == "UP":
head = [snake_pos[0][0], snake_pos[0][1] - snake_size]
elif direction == "DOWN":
head = [snake_pos[0][0], snake_pos[0][1] + snake_size]
# 添加蛇头
snake_pos.insert(0, head)
# 判断是否吃到食物
if snake_pos[0] == food_pos:
food_pos = [random.randrange(1, SCREEN_WIDTH // 10) * 10, random.randrange(1, SCREEN_HEIGHT // 10) * 10]
else:
snake_pos.pop()
# 绘制屏幕
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], food_size, food_size])
for pos in snake_pos:
pygame.draw.rect(screen, WHITE, [pos[0], pos[1], snake_size, snake_size])
# 更新屏幕
pygame.display.update()
# 判断游戏是否结束
if snake_pos[0][0] < 0 or snake_pos[0][0] > SCREEN_WIDTH - snake_size or snake_pos[0][1] < 0 or snake_pos[0][1] > SCREEN_HEIGHT - snake_size:
game_over = True
for pos in snake_pos[1:]:
if snake_pos[0] == pos:
game_over = True
# 控制游戏速度
pygame.time.Clock().tick(20)
# 退出游戏
pygame.quit()
```
这个程序使用了Pygame库,可以在命令行中使用 `pip install pygame` 进行安装。运行程序后,使用键盘上下左右键来控制蛇的移动方向,尽可能地吃到食物,当蛇碰到墙壁或者自己的身体时游戏结束。
阅读全文