patternpythonMinor
Guessing Number(s) Game in Python
Viewed 0 times
gamenumberpythonguessing
Problem
```
import random, os
HIGHSCORE_DATA = []
NUM_DIGITS = 1
MAX_GUESS = 10
if os.path.isfile('./highscore.txt'):
f = open("highscore.txt", "r")
highscore_data = f.readline().split(',')
HIGHSCORE_DATA = highscore_data[0], highscore_data[1]
def increment_difficulty(difficulty = 1):
global NUM_DIGITS
NUM_DIGITS += difficulty
def get_secret_num():
numbers = list(range(10))
random.shuffle(numbers)
secretNum = ''
for i in range(NUM_DIGITS):
secretNum += str(numbers[i])
return secretNum
def get_clues(guess, secretNum):
global NUM_DIGITS
if len(guess) > NUM_DIGITS:
return 'ERROR_LENGTH_TOO_LONG'
if guess == secretNum:
increment_difficulty()
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clues.append('Fermi')
elif guess[i] in secretNum:
clues.append('pico')
if len(clues) == 0:
return 'Bagels'
clues.sort()
return ' ' . join(clues)
def is_only_digits(num):
# Returns True if num is a string of only digits. Otherwise, returns False
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def disp_intro():
global HIGHSCORE
print('[Highscore] Name: {name} | Level: {level}\n'.format(name=HIGHSCORE_DATA[0], level=HIGHSCORE_DATA[1]));
print('I am thinking of a of a %s-digit number. Try to guess what ' % (NUM_DIGITS))
print('The clues I give are . . .')
print('When I say: That means: ')
print('Bagels None of the digits is correct.')
print('Pico One digit is correct but in the wrong position.')
print('Fermi One digit is correct and in the right position.')
while True:
NUM_DIGITS = 1
num_guesses = 1
while num_guesses MAX_GUESS:
print('You ran out of guesses. The answer was %s.' % (secret_nu
import random, os
HIGHSCORE_DATA = []
NUM_DIGITS = 1
MAX_GUESS = 10
if os.path.isfile('./highscore.txt'):
f = open("highscore.txt", "r")
highscore_data = f.readline().split(',')
HIGHSCORE_DATA = highscore_data[0], highscore_data[1]
def increment_difficulty(difficulty = 1):
global NUM_DIGITS
NUM_DIGITS += difficulty
def get_secret_num():
numbers = list(range(10))
random.shuffle(numbers)
secretNum = ''
for i in range(NUM_DIGITS):
secretNum += str(numbers[i])
return secretNum
def get_clues(guess, secretNum):
global NUM_DIGITS
if len(guess) > NUM_DIGITS:
return 'ERROR_LENGTH_TOO_LONG'
if guess == secretNum:
increment_difficulty()
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clues.append('Fermi')
elif guess[i] in secretNum:
clues.append('pico')
if len(clues) == 0:
return 'Bagels'
clues.sort()
return ' ' . join(clues)
def is_only_digits(num):
# Returns True if num is a string of only digits. Otherwise, returns False
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def disp_intro():
global HIGHSCORE
print('[Highscore] Name: {name} | Level: {level}\n'.format(name=HIGHSCORE_DATA[0], level=HIGHSCORE_DATA[1]));
print('I am thinking of a of a %s-digit number. Try to guess what ' % (NUM_DIGITS))
print('The clues I give are . . .')
print('When I say: That means: ')
print('Bagels None of the digits is correct.')
print('Pico One digit is correct but in the wrong position.')
print('Fermi One digit is correct and in the right position.')
while True:
NUM_DIGITS = 1
num_guesses = 1
while num_guesses MAX_GUESS:
print('You ran out of guesses. The answer was %s.' % (secret_nu
Solution
There are a few problems with this code.
I think it's better:
Call it with:
See here
I think the
You're probably better off having a function called
If this is a school exercise and you still haven't learnt how to use dictionaries, you can still do it with two arrays, one for the codes and the other for the descriptions. I think that would still be better than mixing the two things.
There are also quite a few pep8 things to fix, but that's a minor concern right now, you should first fix the other issues.
- In
disp_intro()you're usingglobal HIGHSCORE, but it should actually beglobal HIGHSCORE_DATA
- In case
highscore.txtdoesn't exist, the whole code will fail when trying to accessHIGHSCORE_DATA[0]andHIGHSCORE_DATA[1], so you should have some defaults, likeHIGHSCORE_DATA = ['', 0]
- You're not closing the
highscore.txtfile when reading (usewith) andfis not a nice name (the same goes when writing it).
- You don't need another variable for the high score, it's already what you need
- When reading the highscore file you probably want
rstrip()to remove the extra newline you may (or may not) have
I think it's better:
if os.path.isfile('./highscore.txt'):
with open("highscore.txt", "r") as highscore_file:
HIGHSCORE_DATA = highscore_file.readline().rstrip().split(',')- In
disp_intro()you also needglobal NUM_DIGITS
- You don't need your own function to check if it's all digits, you have the
isdigit()function
- Put the main loop in a
main()function.
Call it with:
if __name__ == '__main__':
main()See here
I think the
get_clues() function is a bit chaotic. It's not consistent because you're returning either a code (ERROR_LENGTH_TOO_LONG) or a description (You got it!). You're also using the same function to determine if you need to increment the difficulty or not. Also, the caller uses the returned description to check if the player has guessed correctly, which is actually the same check you're doing inside of the function.You're probably better off having a function called
compare_guess() which only returns code and the print the description of those codes using a dictionary.If this is a school exercise and you still haven't learnt how to use dictionaries, you can still do it with two arrays, one for the codes and the other for the descriptions. I think that would still be better than mixing the two things.
There are also quite a few pep8 things to fix, but that's a minor concern right now, you should first fix the other issues.
Code Snippets
if os.path.isfile('./highscore.txt'):
with open("highscore.txt", "r") as highscore_file:
HIGHSCORE_DATA = highscore_file.readline().rstrip().split(',')if __name__ == '__main__':
main()Context
StackExchange Code Review Q#158566, answer score: 2
Revisions (0)
No revisions yet.