Здесь вам нужно выделить каждый экран / игровой цикл в его собственную специальную функцию:
Итак, для моего экрана кнопок я могу сделать такую функцию:
def title():
button1 = create_button(100, 100, 250, 80, 'game', game) # This will call the game function later in the file
button2 = create_button(100, 200, 250, 80, 'quit_game', quit_game)
# A list that contains all buttons.
button_list = [button1, button2]
# And so on with the rest of the code...
Для основной игры вы можете сделать то же самое:
def game():
button1 = create_button(100, 100, 250, 80, 'Exit', title) # This button will return you to the title
# And whatever else you need
После этого, в конце файла, вы можете добавить это:
if __name__ == '__main__':
pygame.init()
title() # Call the title first, and then further functions
pygame.quit()
Вы должны заметить, что когда вы активируете функцию обратного вызова кнопок, для разгрузки этого экрана потребуется return
, иначе вы просто наложите игровые петли поверх друг друга.
Итак, во время цикла событий:
if event.button == 1:
for button in button_list:
# `event.pos` is the mouse position.
if button['rect'].collidepoint(event.pos):
# Increment the number by calling the callback
# function in the button list.
button['callback']()
return # Leave the function now that the new one is called.