Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am building a python experiment and am trying to get my code to run every time I hit space but I cant figure out how to do that

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
    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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading