Reputation: 774
I am new to Python and am teaching myself. I am trying to make a slot machine game in Python 3. I want to give the user 0.2 seconds to hit 'enter' to stop it, but I can't figure it out. Here is the code for the slot machine:
def pyslot():
score = 0
while True:
rand1 = random.randint(1, 9)
rand2 = random.randint(1, 9)
rand3 = random.randint(1, 9)
print(str(rand1) + " " + str(rand2) + " " + str(rand3))
time.sleep(0.2)
stop = input("")
if stop == "":
break
if rand1 == rand2 and rand1 == rand3:
print("All three?! No way!")
score += 50
elif (rand1 == rand2 and rand1 != rand3) or (rand2 == rand3 and rand2 != rand1) or (rand1 == rand3 and rand1 != rand2):
print("Two are the same! Not too shabby!")
score += 20
else:
print("No matches... too bad!")
return score
I don't know what is wrong. I have tried multiple solutions on stack overflow, but none work. Any help would be appreciated. Also, how do I clear the last line of print (so the program doesn't print a huge number of slot rolls)
Upvotes: 1
Views: 898
Reputation: 2692
You can use keyboard
module to detect key press and halt the process according to it. First of all you need to install it using: pip install keyboard
, then import in your code. Here is how it could be done (by the way I have refactored conditions since there were quite redundant checks):
import random, time, keyboard
def pyslot():
score = 0
while True:
rand1 = random.randint(1, 9)
rand2 = random.randint(1, 9)
rand3 = random.randint(1, 9)
print(str(rand1) + " " + str(rand2) + " " + str(rand3))
time.sleep(0.2)
if keyboard.is_pressed('enter'):
print("You pressed Enter") # just to test
break
if rand1 == rand2 == rand3:
print("All three?! No way!")
score += 50
elif rand1 == rand2 or rand2 == rand3 or rand1 == rand3:
print("Two are the same! Not too shabby!")
score += 20
else:
print("No matches... too bad!")
return score
pyslot()
Note that you need to run as an administrator to give python access to your keyboard.
sudo python <file_name>
could do the job. Finally, here is the output:
7 9 1
4 4 4
6 4 6
2 9 7
5 7 2
4 5 3
4 9 7
4 5 1
You pressed Enter
No matches... too bad!
Upvotes: 1