我是编程新手,尤其是 PyGame 和 OOP。我不知道如何让按钮在 PyGame 中执行特定命令。我尝试为按钮创建一个类,如果您查看此代码,我可以执行悬停方法/功能作为示例,但是当我按下退出按钮时,我正在努力关闭游戏。我似乎无法理解如何传递一个参数,使 main_menu 在执行 exit 时为假,而 main_game 在执行 play 时为真。
from ColorsAndCoordinates import *
pygame.init()
screen = pygame.display.set_mode((1000, 700))
font = pygame.font.Font("freesansbold.ttf", 42)
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:
Button.display(self, color)
def clicked(self):
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:
pass
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()
pygame.display.update()
皈依舞
相关分类