1

I am making a game and for my startscreen code there is a module called event to handle the mouse click on the button to start the game. But when I run my code, it says event is not defined. It was working fine before this but I decided to go from three while loops to one while loop that will call functions of each screen which I think will be better for restarting the screen. Now when I run it it says that event is not defined in this block of code. Thanks. This is the code that it says is not working:

def StartScreen():
    win.blit (menu,(0, 0))
    button1 = pygame.Rect(200, 400, 100, 50)
    pygame.draw.rect(win, [255, 255, 255], button1)
    if event.type == pygame.MOUSEBUTTONDOWN:
        mouse_pos = event.pos
        if button1.collidepoint(mouse_pos):
            player.start = False
            player.run = True
    Text = pygame.font.Font('freesansbold.ttf', 20)
    TextSurf, TextRect = text_objects("Start!", Text)
    TextRect.center = ((250), (425))
    win.blit(TextSurf, TextRect)
    pygame.display.update()

And here is my new while loop:

while True:
    if player.start == True:
        Start()
    if player.run == True:
        Run()
    if player.gameover == True:
        GameOver()

Please ask if you want the full code.

Baz
  • 159
  • 5
  • Can you share the actual error message? Where is the [mcve]? Please see: [ask]. Variable and function names should follow generally the `lower_case_with_underscores` style. Looking at that loop, what do you think if statements do? – AMC Jan 08 '20 at 18:19
  • What is missing here? Is the issue solved? Is the answer acceptable? – Rabbid76 Feb 05 '20 at 17:22

1 Answers1

1

Use pygame.event.get() to get the events at the begin of the main application loop and pass them the functions:

while True:

    events = pygame.event.get()

    if player.start == True:
        Start(events)
    if player.run == True:
        Run(events)
    if player.gameover == True:
        GameOver(events)

Add an event loop to the functions for the different stages of the game:

def StartScreen(events):
    win.blit (menu,(0, 0))
    button1 = pygame.Rect(200, 400, 100, 50)
    pygame.draw.rect(win, [255, 255, 255], button1)

    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos
            if button1.collidepoint(mouse_pos):
                player.start = False
                player.run = True

    Text = pygame.font.Font('freesansbold.ttf', 20)
    TextSurf, TextRect = text_objects("Start!", Text)
    TextRect.center = ((250), (425))
    win.blit(TextSurf, TextRect)
    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174