#Code should always be in a method or class
#Always start variable names with lowercase, classes could be capital
#input.upper() allows the user to use lower or upper case for each option
import random
def isint(x):
try:
int(x)
return True
except:
return False
print "Invalid guess. "
def getGuessValidator():
while True:
strInput = raw_input("Please enter your guess, between 1 and 42: ")
if isint(strInput) == True:
strInput = int(strInput)
if strInput >42 or strInput <1:
print "Invalid guess. "
else:
return strInput
else:
print "Invalid guess. "
class GuessingGame:
def __init__(self):
self.menu = '''Menu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''
def getNameFromUser(self):
print 'What is your name? '
self.yourName = raw_input()
def displayMenu(self):
while True:
print self.menu
input = raw_input("");
if input.upper() == "V":
while input.upper() == "V":
fileHandle = open ( 'scores.txt', 'r' )
str1 = fileHandle.read()
fileHandle.close()
print str1
break
elif input.upper() == "P":
self.gameMode() #using self. to call method from inside the class
elif input.upper() == "Q":
print "Thank you for playing. "
return
else:
print "Invalid menu choice. "
def gameMode(self):
number = random.randint(1, 42)
guess = -1
self.guessesTaken = 0
while guess != number:
guess = getGuessValidator()
if guess < number:
print 'My number is higher.'
elif guess > number:
print 'My number is lower.'
self.guessesTaken += 1
if guess == number:
print 'Good job, ' + self.yourName + '! You guessed my number in ',self.guessesTaken,' guesses!'
def main():
game = GuessingGame() #Constructing the game
game.getNameFromUser()
game.displayMenu() #runs the menu, which then has all the options
if __name__ == "__main__":
main()
the first 2 def after import random (isint and getguessvalidator) are defined so that the script does not crash when a user inputs a letter instead of a number.
Well I got it to read the text file, as you will see it displays it in reverse order. Ideally I would like to have it in the correct order, which is just switch the highest amount of guesses with the lowest. Though it isn't really that important, using the same code for reading the file but using a w instead of an r then it should write to the file correct or do I need to add more in so that it adds to the file and not overwrite it?
fileHandle = open ( 'scores.txt', 'w' )
str1 = fileHandle.read()
fileHandle.close()
print str1
break
The layout of the file is:
Donald Duck, 14Mickey Mouse, 6Count Duckula, 3
Which when viewing it inside the code prints it like:
Donald Duck 14
Mickey Mouse 6
Count Duckula 3
After the user guesses correctly and it display's their name and the amount of guesses it took. I also need to ask if they would like to save their score to the text file (Yes or No). Either way it will then loop back to the main menu. Anyway enough rambling have a look and let me know how close or far I am from getting it to write to the text file?