Reputation: 131
I'd like to I using the button Yes!
could begin game again not quit from program and come in regularly. How to create it?
def game_over():
Game_over = True
while Game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#[...]
button.draw(450, 500, 'Yes!')
button.draw(720, 500, 'No!', beginning)
pygame.display.update()
clock.tick(FPS)
def game():
global health
Game = True
while Game:
clock.tick(FPS)
for event in pygame.event.get():
#[...]
if event.type == pygame.QUIT:
beginning = False
if health <= 0:
game_over()
#[...]
show_health()
button.draw(20, 80, 'Pause', pause)
pygame.display.update()
all_sprites.update()
def beginning():
Beginning = True
while Beginning:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#[...]
mini_button = Button2(180, 120)
mini_button.draw(570, 200, 'PLAY', game)
mini_button.draw(570, 420, 'QUIT', QUIT)
pygame.display.update()
beginning()
pygame.quit()
Upvotes: 3
Views: 154
Reputation: 210890
The problem with your approach is that it is recursive. beginning
invokes game
, game
invokes game_over
and game_over
again invokes beginning
:
beginning
|
-> game
|
-> game_over
|
-> beginning
|
-> game
|
-> ...
Restructure your code and add a game state variable and functions that change the game state:
game_state = 'beginning'
def start_game():
global game_state
game_state = 'running'
def pause_game():
global game_state
game_state = 'pause'
def game_over():
global game_state
game_state = 'game_over'
def quit_game():
global game_state
game_state = 'quit'
Create a game loop that draws different scenes depending on the state of the game. When a key is pressed, the state of the game changes:
def main():
global game_state
while game_state != 'quit':
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
quit_game()
if game_state == 'beginning':
mini_button = Button2(180, 120)
mini_button.draw(570, 200, 'PLAY', start_game)
mini_button.draw(570, 420, 'QUIT', quit_game)
elif game_state == 'pause':
# [...]
elif game_state == 'running':
for event in event_list:
# [...]
if health <= 0:
game_over()
#[...]
show_health()
button.draw(20, 80, 'Pause', pause_game)
all_sprites.update()
elif game_state == 'game_over':
button.draw(450, 500, 'Yes!', start_game)
button.draw(720, 500, 'No!', quit_game)
pygame.display.update()
clock.tick(FPS)
main()
pygame.quit()
Instead of the global
game_state
variabel you can use a Classe with class methods.
Upvotes: 4