# Guessing Number(s) Game in Python

import random, os

HIGHSCORE_DATA = []
NUM_DIGITS = 1
MAX_GUESS = 10

if os.path.isfile('./highscore.txt'):
f = open("highscore.txt", "r")
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:
secret_num = get_secret_num()

# Debugging Purposes - print(secret_num)

print('I have thought up a number. You have %s guesses to get it.' % (MAX_GUESS))
guess = ''
disp_intro()

while len(guess) != NUM_DIGITS or not is_only_digits(guess):
print("Guess #%s: " % (num_guesses))
guess = input()

clue = get_clues(guess, secret_num)
print(clue)
if clue == 'You got it!':
num_guesses = 1;
print("============================\n")
break;
elif clue == 'ERROR_LENGTH_TOO_LONG':
num_guesses -= 1

num_guesses += 1

#if guess == secret_num:
#    break;
if num_guesses > MAX_GUESS:
print('You ran out of guesses. The answer was %s.' % (secret_num))
highscore_name = input()

f = open('./highscore.txt', 'w')
f.write(highscore_name + "," + str(NUM_DIGITS))
f.close()
break;

print('Do you want to play again? (yes or no)')
if not input().lower().startswith('y'):
break


As the disp_intro says. It will give clues depending on the input given.

Bagels - None of the digits is correct.
Pico - One digit is correct but in the wrong position.
Fermi - One digit is correct and in the right position.

So, basically I just want to see the most concise way this can be written as I'm pretty sure most of the code I wrote is redundant and can be improved by a lot.

## Features

• [X] Generates random SECRET_NUM to guess.
• [X] Shows current High Score.
• [X] Read/Writes the High Score file.
• [X] If length is too long: Do not count tries, and ask again.
• [X] If it's not a number: Do not count tries, and ask again.
• [X] If guess >= MAX_GUESS: Ask for player's name, and then ask to terminate.

There might be more, but I think those are the most important ones.

• This will not work correctly in python 2.7 because of the input() function (the len(guess) will fail), so you're probably better off removing the tag – ChatterOne Mar 23 '17 at 8:38

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:

• 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.