1 回答
TA贡献1851条经验 获得超3个赞
对此有不同的解决方案,例如多态性、动作或事件。
一个明显而简单的解决方案是action在方法中添加一个参数clicked。参数是一个动作函数,当按钮被点击时被调用:
class Button:
# [...]
def clicked(self, action = None):
mouse = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
if action:
action()
创建一个改变状态的函数。考虑将global语句用于全局名称空间中的变量main_menu和main_game:
def action_exit():
global main_menu, main_game
main_menu = False
main_game = True
将动作传递给exit_button.clicked:
while main_menu:
# [...]
exit_button.clicked(action_exit)
再改成Button.display(self, color)方法self.display(color)中display()。
完整示例:
https://i.stack.imgur.com/zYkBf.gif
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1000, 700))
font = pygame.font.Font("freesansbold.ttf", 42)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
class Button:
main_menu = True
def __init__(self, color, x, y, width, height, text):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def display(self, color):
self.color = color
pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
text = font.render(self.text, True, red)
screen.blit(text, (self.x, self.y))
def hover(self, color):
mouse = pygame.mouse.get_pos()
if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
self.display(color)
def clicked(self, action = None):
mouse = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
if action:
action()
def action_exit():
global main_menu, main_game
main_menu = False
main_game = True
play_button = Button(blue, 200, 300, 95, 46, "Play")
exit_button = Button(blue, 700, 300, 95, 46, "Exit")
tutorial_button = Button(blue, 410, 550, 165, 46, "Tutorial")
main_menu = True
main_game = False
while main_menu:
screen.fill(black)
play_button.display(blue)
exit_button.display(blue)
tutorial_button.display(blue)
play_button.hover(black)
exit_button.hover(black)
tutorial_button.hover(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
main_menu = False
exit_button.clicked(action_exit)
pygame.display.update()
添加回答
举报