Я делаю игру сверху вниз, используя ООП.Я выкладываю pygame.USEREVENT + x, где x - это число для перемещения программы по наборам кнопок (т. Е. Кнопки воспроизведения и выхода на кнопки сложности, такие как простые и сложные).Однако программа не возвращается в меню или не повторяет уровень.Как бы я изменил свою программу, чтобы исправить это?
Игра, если она вам нужна: https://github.com/Jaffa609/Stealth-Assassin/upload
Основная программа содержит классы кнопок меню и игровой цикл.Есть два дополнительных файла, Персонаж и Стена, которые являются классами, которые создают и перемещают спрайтов и рисуют стены.Я дошел до того, что игра заканчивается, и я получил кнопку Меню и кнопку повтора на экране, и я использовал операторы печати, чтобы показать, что даже нажатие кнопки регистрируется.Но ничего не происходит.
class GameState(enum.Enum): #A class for all of the game states the menu/game can be in
MENU_PLAYQUIT = 1 #Each of the following is defining a unique value for the state of the game/menu to each of the enumerations
MENU_DIFFICULTY = 2 #^
MENU_LEVELSELECT = 3 #^
GAME_PLAYING = 4 #^
GAME_OVER = 5 #^
class ButtonEvent(enum.IntEnum): # IntEnum so we can convert back to an int for event posting
QUIT = pygame.USEREVENT + 1 #Each of the following is defining a unique value for event codes to which the buttons will send back for each of the enumerations
PLAY = pygame.USEREVENT + 2 #^
EASY = pygame.USEREVENT + 3 #^
MEDIUM = pygame.USEREVENT + 4 #^
HARD = pygame.USEREVENT + 5 #^
VETERAN = pygame.USEREVENT + 6 #^
LEVEL1 = pygame.USEREVENT + 7 #^
LEVEL2 = pygame.USEREVENT + 8 #^
LEVEL3 = pygame.USEREVENT + 9 #^
LEVEL4 = pygame.USEREVENT + 10 #^
CALLMENU = pygame.USEREVENT + 11 #^
RETRY = pygame.USEREVENT + 12 #^
В следующем классе избавились от половины экземпляров метода конструктора и других методов, таких как draw, потому что они были просты и не нужны.
class Button: #This class contains methods for buttons including display and functionality
def __init__(self, buttonname, event_code, buttonx, buttony, buttonwidth, buttonheight, textfile, textx, texty): #Constructor method used to allow classes to intialise attributes
self.event_code = event_code #The event code to enable game/menu state changes
def checkClick(self, mouse_position): #Method which checks if the button has ben pressed within the rectangle's area
result = False #Assumes the mouse click is not within the given dimensions unless proven otherwise. If the result is false in the end then the program and UI remain unaffected
if self.rect.collidepoint(mouse_position): #If the mouse-click is inside our rectangle, post a message to the queue
pygame.event.post(pygame.event.Event(int(self.event_code), {"button_name" : self.buttonname})) #Posts the enumerated value depending on which game state it is in along with the button name
result = True #Result is true therfore action can be taken within the program to progress state
return result #Returns result so its value is known outside this method
Другой класс, называемый ButtonSet, который будет принимать все кнопки для этой части программы и проверять их
elif game_state == GameState.GAME_OVER: #If the game has been finished
gameOver_buttons.anyClicked(click_location)
Выше и ниже находится в цикле основной игры
elif event.type in [ButtonEvent.CALLMENU, ButtonEvent.RETRY]:
if event.type == ButtonEvent.CALLMENU:
import menu
if event.type == ButtonEvent.RETRY:
game_state = GameState.GAME_PLAYING