如何通过python实现贪吃蛇游戏,能给我示例代码吗
时间: 2023-06-01 11:07:16 浏览: 57
可以的,以下是一个简单的贪吃蛇游戏的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义窗口大小和标题
window_width = 640
window_height = 480
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 定义游戏方块大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,用于绘制蛇
def draw_snake(snake_list):
for snake_block in snake_list:
pygame.draw.rect(game_display, green, [
snake_block[0], snake_block[1], block_size, block_size])
# 定义函数,用于显示消息
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [window_width/2, window_height/2])
# 定义函数,用于主循环
def game_loop():
# 初始化游戏变量
game_exit = False
game_over = False
snake_list = []
snake_length = 1
clock = pygame.time.Clock()
# 将蛇放在屏幕中心
lead_x = window_width / 2
lead_y = window_height / 2
lead_x_change = 0
lead_y_change = 0
# 随机生成食物位置
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('游戏已结束,按 Q 退出,按 C 重新开始', red)
pygame.display.update()
# 循环处理事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
elif 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
# 判断是否撞到边界
if lead_x >= window_width or lead_x < 0 or lead_y >= window_height or lead_y < 0:
game_over = True
# 移动蛇头
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制背景
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]
# 判断是否吃到食物
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
# 判断是否撞到自己
for snake_body in snake_list[:-1]:
if snake_body == snake_head:
game_over = True
# 绘制蛇
draw_snake(snake_list)
# 刷新屏幕
pygame.display.update()
# 设置帧率
clock.tick(15)
# 退出pygame
pygame.quit()
quit()
# 启动游戏循环
game_loop()
```