HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Guessing Number(s) Game in Python

Submitted by: @import:stackexchange-codereview··
0
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

Solution

There are a few problems with this code.

  • In disp_intro() you're using global HIGHSCORE, but it should actually be global HIGHSCORE_DATA



  • In case highscore.txt doesn't exist, the whole code will fail when trying to access HIGHSCORE_DATA[0] and HIGHSCORE_DATA[1], so you should have some defaults, like HIGHSCORE_DATA = ['', 0]



  • You're not closing the highscore.txt file when reading (use with) and f is 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 need global 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.