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.
JavaScript
x
26
26
1
import random
2
import keyboard
3
4
food = 5
5
x = 0
6
y = 0
7
8
if keyboard.is_pressed('space'):
9
bobsDecision = random.randint(0,1)
10
if bobsDecision == 1:
11
print ('bob ate')
12
food = 5
13
else:
14
xoy = random.randint(1,4)
15
if xoy == 1:
16
x = x + 1
17
elif xoy == 2:
18
x = x - 1
19
elif xoy == 3:
20
y = y + 1
21
elif xoy == 4:
22
y = y - 1
23
food = food - 1
24
print ('the cords are ', x, " ", y)
25
print ('The food supply is ', food)
26
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:
JavaScript
1
31
31
1
import random
2
import keyboard
3
4
food = 5
5
x = 0
6
y = 0
7
8
while True:
9
keyboard.read_key() # an important inclusion thanks to @wkl
10
if keyboard.is_pressed('esc'):
11
break
12
13
elif keyboard.is_pressed('space'):
14
bobsDecision = random.randint(0,1)
15
if bobsDecision == 1:
16
print ('bob ate')
17
food = 5
18
else:
19
xoy = random.randint(1,4)
20
if xoy == 1:
21
x = x + 1
22
elif xoy == 2:
23
x = x - 1
24
elif xoy == 3:
25
y = y + 1
26
elif xoy == 4:
27
y = y - 1
28
food = food - 1
29
print ('the cords are ', x, " ", y)
30
print ('The food supply is ', food)
31