在Pygame中添加主菜单和重试菜单可以通过以下步骤实现:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My Game")
def show_main_menu():
# 清空屏幕
screen.fill((0, 0, 0))
# 显示主菜单标题
font = pygame.font.Font(None, 36)
title = font.render("Main Menu", True, (255, 255, 255))
title_rect = title.get_rect(center=(400, 200))
screen.blit(title, title_rect)
# 显示菜单选项
font = pygame.font.Font(None, 24)
option1 = font.render("Start Game", True, (255, 255, 255))
option1_rect = option1.get_rect(center=(400, 300))
screen.blit(option1, option1_rect)
option2 = font.render("Quit", True, (255, 255, 255))
option2_rect = option2.get_rect(center=(400, 350))
screen.blit(option2, option2_rect)
# 更新屏幕显示
pygame.display.flip()
def show_retry_menu():
# 清空屏幕
screen.fill((0, 0, 0))
# 显示重试菜单标题
font = pygame.font.Font(None, 36)
title = font.render("Retry Menu", True, (255, 255, 255))
title_rect = title.get_rect(center=(400, 200))
screen.blit(title, title_rect)
# 显示菜单选项
font = pygame.font.Font(None, 24)
option1 = font.render("Retry", True, (255, 255, 255))
option1_rect = option1.get_rect(center=(400, 300))
screen.blit(option1, option1_rect)
option2 = font.render("Quit", True, (255, 255, 255))
option2_rect = option2.get_rect(center=(400, 350))
screen.blit(option2, option2_rect)
# 更新屏幕显示
pygame.display.flip()
running = True
main_menu = True
retry_menu = False
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_RETURN:
if main_menu:
if option1_rect.collidepoint(pygame.mouse.get_pos()):
# 开始游戏
main_menu = False
retry_menu = False
# 添加开始游戏的逻辑代码
if option2_rect.collidepoint(pygame.mouse.get_pos()):
# 退出游戏
running = False
if retry_menu:
if option1_rect.collidepoint(pygame.mouse.get_pos()):
# 重试游戏
main_menu = False
retry_menu = False
# 添加重试游戏的逻辑代码
if option2_rect.collidepoint(pygame.mouse.get_pos()):
# 退出游戏
running = False
if main_menu:
show_main_menu()
if retry_menu:
show_retry_menu()
通过以上步骤,你可以在Pygame中添加主菜单和重试菜单。你可以根据需要自定义菜单的样式和功能,并在相应的位置添加游戏逻辑代码。
领取专属 10元无门槛券
手把手带您无忧上云