Reputation: 3
I'm coding a counting game where the computer generates a 3-digit number, and you have to guess it. If you get a digit in the right spot, you get a strike, and if you get a digit in the wrong spot, you get a ball. I keep getting an error on line 12 of my code. Can someone help?
x = random.randint(1, 9)
y = random.randint(1, 9)
z = random.randint(1, 9)
while True:
try:
user_guess_unlisted = int(input('What number do you want to guess?'))
except:
continue
break
number_to_guess = [x, y, z]
user_guess = list(user_guess_unlisted)
b = 0
s = 0
rloop = 1
while rloop:
if user_guess[0] == number_to_guess[0]:
s = s + 1
if user_guess[0] == number_to_guess[1]:
b = b + 1
if user_guess[0] == number_to_guess[2]:
b = b + 1
if user_guess[1] == number_to_guess[0]:
b = b + 1
if user_guess[1] == number_to_guess[1]:
s = s + 1
if user_guess[1] == number_to_guess[2]:
b = b + 1
if user_guess[2] == number_to_guess[0]:
b = b + 1
if user_guess[2] == number_to_guess[1]:
b = b + 1
if user_guess[2] == number_to_guess[2]:
s = s + 1
print(str(s) + "S " + str(b) + "B")
if s != 3:
b = 0
s = 0
userguessunlisted = input('what number do you want to guess?')
userguess = list(userguessunlisted)
if s == 3:
print('you win!')
rloop = 0
Upvotes: 0
Views: 33
Reputation: 3624
You can't convert an integer to a list.
You can use this:
from random import randint
num = str(randint(0, 999)).zfill(3)
while True:
while True:
guess = input('Guess a number: ').zfill(3)
if guess.isdigit():
if int(guess) < 1000:
break
b = s = 0
for i, n in enumerate(num):
for j, g in enumerate(guess):
if n == g:
if i == j:
s += 1
else:
b += 1
print('Balls:', b)
print('Strikes:', s)
if s == 3:
break
print('')
Output:
Guess a number: 123
Balls: 0
Strikes: 0
Guess a number: 456
Balls: 2
Strikes: 0
Guess a number: 654
Balls: 1
Strikes: 1
Guess a number: 647
Balls: 1
Strikes: 1
Guess a number: 657
Balls: 2
Strikes: 1
Guess a number: 675
Balls: 0
Strikes: 3
Upvotes: 1