Skip to content
Advertisement

Execute code whenever the space bar is pressed?

I am making this kind of a game but it isn’t really a game so basically I want this to run every time I hit space but it doesn’t work no matter what I try so I would be really thankful if somebody could have helped me out on this.

import random
import keyboard

food = 5
x = 0 
y = 0 

if keyboard.is_pressed('space'):
    bobsDecision = random.randint(0,1)
    if bobsDecision == 1:
        print ('bob ate')
        food = 5
    else:
        xoy = random.randint(1,4)
        if xoy == 1: 
            x = x + 1
        elif xoy == 2:
            x = x - 1
        elif xoy == 3:
            y = y + 1
        elif xoy == 4:
            y = y - 1
        food = food - 1
        print ('the cords are ', x, " ", y)
        print ('The food supply is ', food)

Advertisement

Answer

You need to put the if statement in a while loop. But ALSO be sure to have some kind of exit code. Below, I used the keypress esc to stop the while loop:

import random
import keyboard

food = 5
x = 0 
y = 0 

while True:
    keyboard.read_key() # an important inclusion thanks to @wkl
    if keyboard.is_pressed('esc'):
        break
    
    elif keyboard.is_pressed('space'):
        bobsDecision = random.randint(0,1)
        if bobsDecision == 1:
            print ('bob ate')
            food = 5
        else:
            xoy = random.randint(1,4)
            if xoy == 1: 
                x = x + 1
            elif xoy == 2:
                x = x - 1
            elif xoy == 3:
                y = y + 1
            elif xoy == 4:
                y = y - 1
            food = food - 1
            print ('the cords are ', x, " ", y)
            print ('The food supply is ', food)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement