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

After some more playing around, I resolved that it was the scores.txt file that was causing the traceback errors. When it only has the original data, then it works fine, but when saving new scores to it that is when it causes the traceback error to happen.

So how do I revert this code back to having no functions, classes, methods, etc. As I have being told that having the definitions are not allowed, although it only states I cannot define my own functions and should be able to use in-built functions. I originally got 9 out of 10 for it with functions.

You put function inside method by adding to def line as first parameter self and by calling it with self.func() instead of func().

I do not see in assignment that you must not write functions, they should only be used inside class.

You are to plan and code a number guessing game, as described by the information and sample output below. Use what you have learned in class, but do not define any of your own functions.

That is an excerpt from the outline, although I read it as, I can use any in-built functions that are with python by default. So the only function I have made that is my own is the getGuessValidator from lines 16 to 26. I can actually put the full details up if you need them from the pdf.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.