Search code examples
pythonfunctioncall

Python function call on player input


I have a problem in python with pygame. I want to "jump to" a function after a specific input is made by the user (In this case when up arrow key is pressed down), and then while in that function (start1) i call back to main() again and when "up arrow key" is pressed again i want to get into start()

When i run the program i get this:

RecursionError: maximum recursion depth exceeded

Any advice?

Here is the code:

def main(text, func):

    exit = False
    while not exit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                func

            if event.key == pygame.K_DOWN:
                pygame.quit()
                quit()

    screen.fill(black)

    text = str(text)
    font = pygame.font.SysFont('georgia', 16)
    message = font.render(text, True, white)
    screen.blit(message, (screen_width / 2, screen_height / 2))

    pygame.display.flip()
    clock.tick(30)



def start():
    main("Hello, press key-up to get to start 1!", start1())


def start1():
    os.system('cls')
    main("Good, Back to start on Key-up", start())



start()

Solution

  • you're not passing start1 and start functions to main but you call them instead before main is even called.

    def start():
        main("Hello, press key-up to get to start 1!", start1())
    
    def start1():
        os.system('cls')
        main("Good, Back to start on Key-up", start())
    

    start calls start1, which calls start when evaluating the parameters of main in each routine. main hasn't a chance to be called: infinite ping-pong recursion occurs first.

    change to:

    def start():
        main("Hello, press key-up to get to start 1!", start1)
    
    def start1():
        os.system('cls')
        main("Good, Back to start on Key-up", start)
    

    and in main replace func by func() in the code like this to call your function here:

    if event.key == pygame.K_UP:
        func()