用Python如何写一个贪吃蛇游戏
时间: 2024-04-25 11:06:01 浏览: 7
Python写贪吃蛇游戏可以使用Pygame库来实现。以下是一个简单的贪吃蛇游戏的示例代码:
```python
import pygame
import random
pygame.init()
# 游戏窗口大小
window_width = 800
window_height = 600
# 贪吃蛇方块大小和速度
block_size = 20
snake_speed = 10
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# 定义字体
font = pygame.font.SysFont(None, 25)
# 显示消息函数
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [window_width / 6, window_height / 3])
# 游戏主循环函数
def game_loop():
game_exit = False
game_over = False
# 贪吃蛇初始位置和长度
lead_x = window_width / 2
lead_y = window_height / 2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 食物初始位置
food_x = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
# 游戏主循环
while not game_exit:
# 如果游戏结束,显示游戏结束消息
while game_over:
game_display.fill(white)
message_to_screen("Game Over, press C to play again or Q to quit", red)
pygame.display.update()
# 处理按键事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
# 处理按键事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 移动贪吃蛇
lead_x += lead_x_change
lead_y += lead_y_change
# 判断贪吃蛇是否碰到边界
if lead_x >= window_width or lead_x < 0 or lead_y >= window_height or lead_y < 0:
game_over = True
# 绘制食物和贪吃蛇
game_display.fill(white)
pygame.draw.rect(game_display, red, [food_x, food_y, block_size, block_size])
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
for segment in snake_list:
pygame.draw.rect(game_display, black, [segment[0], segment[1], block_size, block_size])
pygame.display.update()
# 如果贪吃蛇吃到食物,分数加1,贪吃蛇长度加1,重新生成食物
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
snake_length += 1
# 控制游戏帧率
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
game_loop()
```
上述代码使用了Pygame库实现了一个简单的贪吃蛇游戏。该游戏使用方向键来控制贪吃蛇的移动,当贪吃蛇吃到食物时,分数加1,贪吃蛇长度加1,重新生成食物。当贪吃蛇碰到边界或自己时,游戏结束。