Python的贪吃蛇游戏
时间: 2024-01-15 09:18:42 浏览: 72
贪吃蛇游戏是一款经典的游戏,玩家通过控制一条蛇在游戏界面上移动,吃掉食物来增长身体长度,同时要避免撞到墙壁或自己的身体。下面是一个简单的Python贪吃蛇游戏的示例:
```python
import pygame
import random
# 游戏界面的宽度和高度
WIDTH = 800
HEIGHT = 600
# 蛇身和食物的大小
SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏界面
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和速度
snake_x = WIDTH // 2
snake_y = HEIGHT // 2
snake_speed_x = 0
snake_speed_y = 0
# 定义蛇的初始长度和身体
snake_length = 1
snake_body = []
# 定义食物的初始位置
food_x = random.randint(0, WIDTH - SIZE) // SIZE * SIZE
food_y = random.randint(0, HEIGHT - SIZE) // SIZE * SIZE
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake_speed_x = 0
snake_speed_y = -SIZE
elif event.key == pygame.K_DOWN:
snake_speed_x = 0
snake_speed_y = SIZE
elif event.key == pygame.K_LEFT:
snake_speed_x = -SIZE
snake_speed_y = 0
elif event.key == pygame.K_RIGHT:
snake_speed_x = SIZE
snake_speed_y = 0
# 更新蛇的位置
snake_x += snake_speed_x
snake_y += snake_speed_y
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
snake_length += 1
food_x = random.randint(0, WIDTH - SIZE) // SIZE * SIZE
food_y = random.randint(0, HEIGHT - SIZE) // SIZE * SIZE
# 更新蛇的身体
snake_body.append((snake_x, snake_y))
if len(snake_body) > snake_length:
del snake_body[0]
# 判断蛇是否撞到墙壁或自己的身体
if (snake_x < 0 or snake_x >= WIDTH or
snake_y < 0 or snake_y >= HEIGHT or
(snake_x, snake_y) in snake_body[:-1]):
running = False
# 绘制游戏界面
screen.fill(BLACK)
for body_part in snake_body:
pygame.draw.rect(screen, WHITE, (body_part[0], body_part[1], SIZE, SIZE))
pygame.draw.rect(screen, RED, (food_x, food_y, SIZE, SIZE))
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这是一个简单的贪吃蛇游戏示例,使用了pygame库来实现游戏界面的绘制和事件处理。玩家可以通过上下左右键来控制蛇的移动,吃到食物后蛇的长度会增加,当蛇撞到墙壁或自己的身体时游戏结束。
阅读全文