#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
from operator import itemgetter
def isint(x):
try:
int(x)
return True
except:
return False
print "Invalid guess. "
def getGuessValidator(): #Used in conjunction with isint function above to validate the guess entered is a integer and not anything else
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 = '''\nMenu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''
def getNameFromUser(self):
self.yourName = raw_input('What is your name? ')
def displayMenu(self):
while True:
print self.menu
input = raw_input("")
if input.upper() == "V": #allows the user to use v or V instead of restricting the user the just using upper case letter
fileHandle = open ( 'scores.txt', 'r' )
str1 = fileHandle.read().strip()
fileHandle.close()
list1 = str1.split("\n")
list2 = []
for str2 in list1:
list3 = str2.split(",")
list3[1]= int(list3[1])
list2.append(list3)
list2 = sorted(list2, key=itemgetter(1)) #this will sort the scores.txt file into 2 lists and then merge them back into 1 list that is sorted by the score.
print "High Scores: "
for str2 in list2:
print "%-20s %5s" %(str2[0], str2[1])
elif input.upper() == "P": #allows the user to use p or P instead of restricting the user the just using upper case letter
self.gameMode() #using self. to call method from inside the class
elif input.upper() == "Q": #allows the user to use q or Q instead of restricting the user the just using upper case letter
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!'
self.saveScore()
def saveScore(self):
print "\nWould you like to save your score? (Y)es or (N)o:"
inp = raw_input().upper(); #allows upper or lower case to be used
if inp == "Y":
saveStr = self.yourName + ', ' + str(self.guessesTaken) + "\n"
fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt instead of overwriting the original data
fileHandle.write(saveStr)
fileHandle.close()
print "Saving high scores file... "
return
def main():
game = GuessingGame() #Constructing the game
game.getNameFromUser()
game.displayMenu() #Runs the menu, which then displays all the menu options
if __name__ == "__main__":
main()
This was working before and now I am getting these three traceback errors:
Traceback (most recent call last):
File "G:\GuessingGame.py", line 104, in <module>
main()
File "G:\GuessingGame.py", line 101, in main
game.displayMenu() #Runs the menu, which then displays all the menu options
File "G:\GuessingGame.py", line 51, in displayMenu
list3[1]= int(list3[1])
IndexError: list index out of range
These errors only appear after I have saved a score to the scores.txt file, before adding a new score to it, everything works fine. I also need to rewrite it without functions/classes/methods/etc which will make it have a lot more lines of code.