Execute code whenever the space bar is pressed?

Question:

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)
Asked By: Storm Gaming

||

Answers:

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)
Answered By: Michael S.

Your code runs once and immediately skips over keyboard.is_pressed("space"), and then exits.

What you want to do instead is to loop forever, and use the keyboard module’s read_key functionality to make it wait for a keypress.

An example of this is this – I also added support for exiting the loop/game with esc.

import random
import keyboard

food = 5
x = 0 
y = 0 

while True:
    keyboard.read_key()
    if keyboard.is_pressed("esc"):
        print("Stopping play...")
        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)
Answered By: wkl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.