I've been learning Python for a few weeks and I created a simple game where you convert binary numbers to decimal. It shows you n binary numbers and you are supposed to enter the numbers in decimal system in sequence as a password. After failing three times you lose. I'd like to implement it into a bigger game later.
Here's the code:
import random
# Conver decimal to binary.
def toBin(i):
bin = "{0:b}".format(i)
return bin
# Generate random password and it's binary version.
def generatePassword(n):
password = []
passwordBin = []
for i in range(n):
a = random.randint(0, 9)
password.append(a)
passwordBin.append(toBin(a))
return password, passwordBin
# Prints the binary password and a frame.
def printPassword(password):
print(12 * '#')
for i in range(len(password[1]) + 4):
if i <= 1:
print(2 * '#' + 8 * ' ' + 2 * '#')
elif i <= 5:
print(2 * '#' + password[1][i - 2].rjust(4, '0').center(8) + 2 * '#')
else:
print(2 * '#' + 8 * ' ' + 2 * '#')
print(12 * '#')
# The game loop.
def puzzle(n):
password = generatePassword(n)
win = False
endLoop = False
attempts = 3
while endLoop is False:
# Check remaining attempts.
if attempts > 0:
printPassword(password)
print('Attempts remaining: ' + str(attempts) + '\n')
# Looping through password numbers.
for i in range(n):
print('Number ' + str(i + 1), '\t\t', end='')
# Input and check for ValueError.
try:
inp = int(input())
except ValueError:
print('You can only enter numbers.')
break
# Is input correct?
if inp == password[0][i]:
print('CORRECT')
else:
attempts -= 1
print('WRONG\n')
break
# End loop and win.
else:
endLoop = True
win = True
# End loop.
else:
endLoop = True
# Check win condition.
if win is True:
print('ACCESS GRANTED')
else:
print('ACCESS DENIED')
# Run the game.
puzzle(4)
Are there any ways to improve my code, expecially the puzzle(n) function? The conditions and loops took me some time to get working and still kinda confuse me. I hope there aren't any bugs.