问题如下:比方说,在我的游戏中,我有两个菜单,实现为不同的游戏循环。假设一个是红色菜单,另一个是绿色菜单。
在每个菜单中,都有一个按钮,当按下该按钮时,将启动另一个菜单。如果按钮在屏幕中的相同位置,则在加载新菜单时,按下其中一个按钮会导致按下另一个按钮,从而使用户返回到旧菜单。
下面是一个代码示例-我如何修复此问题?
import pygame
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
class Game:
def __init__(self):
# When true, the game will end:
self.done = False
self.screen = pygame.display.set_mode((600, 400))
self.clock = pygame.time.Clock()
# List storing all events:
self.all_events = []
self.show_red_page()
def update(self):
self.all_events = []
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
else:
self.all_events.append(event)
def show_red_page(self):
button = Button(self, pygame.rect.Rect((100, 100), (50, 50)), BLACK)
while not self.done:
self.screen.fill(RED)
self.update()
# If the button is clicked, launch the other page:
if button.clicked():
self.show_green_page()
# Draw button:
button.draw()
self.update()
pygame.display.flip()
self.clock.tick(60)
def show_green_page(self):
# Same as red page, but different colors:
button = Button(self, pygame.rect.Rect((100, 100), (50, 50)), WHITE)
while not self.done:
self.screen.fill(GREEN)
# If the button is clicked, launch the other page:
if button.clicked():
self.show_red_page()
# Draw button:
button.draw()
self.update()
pygame.display.flip()
self.clock.tick(60)
class Button:
def __init__(self,game, rect, color):
self.game = game
self.rect = rect
self.image = pygame.Surface(self.rect.size)
self.image.fill(color)
def draw(self):
pygame.display.get_surface().blit(self.image, self.rect)
def hovering(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def clicked(self):
return self.hovering() and pygame.MOUSEBUTTONUP in [event.type for event in self.game.all_events]
Game()
检查更新函数for循环中的点击情况。这注册为一次点击,不像在while循环之外检查点击,而是使用不同的函数。尝试:
python
#check if left clicked:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button = 1:
#check if mouse is hovered over the button, if so:
#function here
希望这对每个菜单都有帮助,祝你的游戏好运!