import pygame
import time
import random
# 初始化Pygame
pygame.init()
# 颜色定义
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
light_blue = (100, 200, 255)
gray = (200, 200, 200)
# 游戏窗口尺寸
dis_width = 800
dis_height = 600
# 创建游戏窗口
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏')
# 游戏时钟
clock = pygame.time.Clock()
# 蛇的大小和速度
snake_block = 10
snake_speed = 15 # 全局变量
# 字体设置
font_style = pygame.font.SysFont("simhei", 25)
score_font = pygame.font.SysFont("simhei", 35)
button_font = pygame.font.SysFont("simhei", 30)
# 按钮类
class Button:
def __init__(self, x, y, width, height, text, color, hover_color, action=None):
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.color = color
self.hover_color = hover_color
self.action = action
def draw(self, surface):
# 检查鼠标是否悬停在按钮上
if self.is_hovered():
pygame.draw.rect(surface, self.hover_color, self.rect)
else:
pygame.draw.rect(surface, self.color, self.rect)
# 绘制按钮文本
text_surf = button_font.render(self.text, True, black)
text_rect = text_surf.get_rect(center=self.rect.center)
surface.blit(text_surf, text_rect)
def is_hovered(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def is_clicked(self, event):
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
return self.is_hovered()
return False
# 显示分数
def Your_score(score):
value = score_font.render(f"分数: {score}", True, yellow)
dis.blit(value, [0, 0])
# 绘制蛇
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])
# 显示消息
def message(msg, color, y_offset=0):
mesg = font_style.render(msg, True, color)
mesg_rect = mesg.get_rect(center=(dis_width / 2, dis_height / 3 + y_offset))
dis.blit(mesg, mesg_rect)
# 重置游戏状态(用于重新开始)
def reset_game():
global snake_speed
snake_speed = 15
return {
'x1': dis_width / 2,
'y1': dis_height / 2,
'x1_change': 0,
'y1_change': 0,
'snake_List': [],
'Length_of_snake': 1,
'foodx': round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0,
'foody': round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
}
# 创建按钮
def create_buttons():
button_width = 150
button_height = 50
button_y = dis_height / 2
# 重新开始按钮
restart_btn = Button(
dis_width / 2 - button_width - 20,
button_y,
button_width,
button_height,
"重新开始",
green,
(100, 255, 100),
"restart"
)
# 退出按钮
quit_btn = Button(
dis_width / 2 + 20,
button_y,
button_width,
button_height,
"退出",
red,
(255, 100, 100),
"quit"
)
return [restart_btn, quit_btn]
# 游戏主逻辑
def gameLoop():
global snake_speed
game_over = False
game_close = False
# 创建按钮
buttons = create_buttons()
# 初始化游戏状态
game_state = reset_game()
x1 = game_state['x1']
y1 = game_state['y1']
x1_change = game_state['x1_change']
y1_change = game_state['y1_change']
snake_List = game_state['snake_List']
Length_of_snake = game_state['Length_of_snake']
foodx = game_state['foodx']
foody = game_state['foody']
while not game_over:
while game_close:
# 游戏结束界面
dis.fill(black)
message("游戏结束!", red, -50)
message(f"最终分数: {Length_of_snake - 1}", yellow)
# 绘制按钮
for button in buttons:
button.draw(dis)
pygame.display.update()
# 处理游戏结束后的输入
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
game_close = False
# 检查按钮点击
for button in buttons:
if button.is_clicked(event):
if button.action == "restart":
# 重新开始游戏
game_state = reset_game()
x1 = game_state['x1']
y1 = game_state['y1']
x1_change = game_state['x1_change']
y1_change = game_state['y1_change']
snake_List = game_state['snake_List']
Length_of_snake = game_state['Length_of_snake']
foodx = game_state['foodx']
foody = game_state['foody']
game_close = False
elif button.action == "quit":
game_over = True
game_close = False
# 处理键盘输入
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and x1_change == 0:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT and x1_change == 0:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP and y1_change == 0:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN and y1_change == 0:
y1_change = snake_block
x1_change = 0
# 碰撞检测(墙壁)
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
# 更新位置
x1 += x1_change
y1 += y1_change
dis.fill(black)
# 绘制食物
pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
# 更新蛇的身体
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# 保持蛇的长度
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 碰撞检测(自身)
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# 绘制蛇和分数
our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
# 检测是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 随着分数增加,提高速度
if Length_of_snake % 5 == 0 and snake_speed < 30:
snake_speed += 1
# 控制游戏速度
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 启动游戏
gameLoop()
新建一个项目,然后复制上面的代码,粘贴在.py文件中,

安装运行所需的游戏库

开始运行,就能游玩了