这里使用Python的pygame库实现的简单小游戏:贪吃蛇。首先确保你已经安装了pygame库,如果没有安装,可以使用以下命令安装:
```bash
pip install pygame
```
接下来是贪吃蛇游戏的代码:
```python
import pygame
import sys
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇和食物的大小
snake_size = 20
food_size = 20
# 定义蛇的初始位置
snake_pos = [[100, 100], [80, 100], [60, 100]]
# 定义食物的初始位置
food_pos = [300, 300]
# 定义蛇的移动方向
move_direction = "right"
# 游戏主循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and move_direction != "down":
move_direction = "up"
elif event.key == pygame.K_DOWN and move_direction != "up":
move_direction = "down"
elif event.key == pygame.K_LEFT and move_direction != "right":
move_direction = "left"
elif event.key == pygame.K_RIGHT and move_direction != "left":
move_direction = "right"
# 更新蛇的位置
if move_direction == "up":
new_pos = [snake_pos[0][0], snake_pos[0][1] - snake_size]
elif move_direction == "down":
new_pos = [snake_pos[0][0], snake_pos[0][1] + snake_size]
elif move_direction == "left":
new_pos = [snake_pos[0][0] - snake_size, snake_pos[0][1]]
elif move_direction == "right":
new_pos = [snake_pos[0][0] + snake_size, snake_pos[0][1]]
snake_pos.insert(0, new_pos)
if snake_pos[0] == food_pos:
food_pos = [random.randrange(1, screen_width // food_size) * food_size,
random.randrange(1, screen_height // food_size) * food_size]
else:
snake_pos.pop()
# 检查蛇是否撞到墙壁或自己
if (snake_pos[0][0] < 0 or snake_pos[0][0] >= screen_width or
snake_pos[0][1] < 0 or snake_pos[0][1] >= screen_height or
snake_pos[0] in snake_pos[1:]):
pygame.quit()
sys.exit()
# 绘制游戏画面
screen.fill(black)
for pos in snake_pos:
pygame.draw.rect(screen, white, (pos[0], pos[1], snake_size, snake_size))
pygame.draw.rect(screen, red, (food_pos[0], food_pos[1], food_size, food_size))
# 更新游戏画面
pygame.display.flip()
# 控制游戏速度
pygame.time.Clock().tick(10)
```
将以上代码保存为一个名为snake.py的文件,然后在命令行中运行`python snake.py`即可开始游戏。使用方向键控制蛇的移动方向。
喜欢的话点个赞吧