import pygame
import random
import time
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 600
screen_height = 600
# 设置蛇的初始长度
snake_length = 3
# 设置蛇的初始位置
snake_x = [250, 240, 230]
snake_y = [250, 250, 250]
# 蛇的移动方向
direction = 'right'
# 蛇的每一个格子大小
size = 10
# 食物的初始位置
food_x = round(random.randrange(0, screen_width - size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - size) / 10.0) * 10.0
# 设置背景颜色
bg_color = (255, 255, 255)
# 设置蛇的颜色
snake_color = (20, 20, 200)
# 设置食物的颜色
food_color = (200, 20, 20)
# 设置得分和速度
score = 0
speed = 10
# 设置游戏是否结束的标志
game_over = False
# 设置游戏是否暂停的标志
pause = False
# 设置游戏是否开始的标志
start = False
# 设置游戏是否重置的标志
reset = False
# 设置游戏的字体
font = pygame.font.SysFont('arial', 20)
# 设置游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏窗口标题
pygame.display.set_caption('贪吃蛇游戏')
# 定义按键处理函数
def key_handle():
global direction, snake_x, snake_y, food_x, food_y, speed, score, game_over, pause, start, reset
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if not start:
start = True
elif pause:
if event.key == pygame.K_p:
pause = False
else:
if event.key == pygame.K_p:
pause = True
elif event.key == pygame.K_r:
reset = True
elif 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'
# 定义蛇移动函数
def snake_move():
global snake_x, snake_y, food_x, food_y, score, game_over, direction, reset
if not pause and not game_over and not reset:
if direction == 'right':
snake_x.insert(0, snake_x[0] + size)
if direction == 'left
评论已关闭