写一个贪吃蛇游戏,用python书写
时间: 2024-04-17 22:24:42 浏览: 83
当然可以!下面是一个简单的贪吃蛇游戏的Python代码示例:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 蛇身和食物大小
CELL_SIZE = 20
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化Pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 蛇的初始位置和初始长度
snake_head = [WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2]
snake_body = [[snake_head[0], snake_head[1]], [snake_head[0]-CELL_SIZE, snake_head[1]], [snake_head[0]-2*CELL_SIZE, snake_head[1]]]
# 初始移动方向
direction = "RIGHT"
# 食物的初始位置
food_position = [random.randrange(1, (WINDOW_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT // CELL_SIZE)) * CELL_SIZE]
# 游戏结束标志位
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 监听键盘事件,改变蛇的移动方向
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "DOWN":
direction = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
direction = "DOWN"
elif event.key == pygame.K_LEFT and direction != "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
direction = "RIGHT"
# 根据移动方向改变蛇头位置
if direction == "UP":
snake_head[1] -= CELL_SIZE
elif direction == "DOWN":
snake_head[1] += CELL_SIZE
elif direction == "LEFT":
snake_head[0] -= CELL_SIZE
elif direction == "RIGHT":
snake_head[0] += CELL_SIZE
# 判断是否吃到食物
if snake_head == food_position:
# 生成新的食物位置
food_position = [random.randrange(1, (WINDOW_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT // CELL_SIZE)) * CELL_SIZE]
else:
# 移除蛇尾
snake_body.pop()
# 判断游戏是否结束
if snake_head[0] < 0 or snake_head[0] >= WINDOW_WIDTH or snake_head[1] < 0 or snake_head[1] >= WINDOW_HEIGHT:
game_over = True
elif snake_head in snake_body[1:]:
game_over = True
# 添加蛇头到蛇身
snake_body.insert(0, list(snake_head))
# 绘制游戏窗口
window.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(window, WHITE, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE))
pygame.draw.rect(window, RED, pygame.Rect(food_position[0], food_position[1], CELL_SIZE, CELL_SIZE))
# 刷新游戏窗口
pygame.display.flip()
# 控制游戏帧率
clock.tick(10)
# 退出游戏
pygame.quit()
```
这个代码实现了一个简单的贪吃蛇游戏,你可以运行它来尝试玩一下。希望对你有帮助!
阅读全文