Guessing Game with functions, classes, methods, etc

#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():
    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":
                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":
                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!'

            self.saveScore()
    def saveScore(self):
        print "\nWould you like to save your score? (Y)es or (N)o:"
        inp = raw_input().upper();
        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 has all the options

if __name__ == "__main__":
    main()

The same code minus defined functions, classes, etc

import random
from operator import itemgetter

isint(x)
try:
    int(x)
    return True
except:
    return False
print "Invalid guess. "

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

__init__(self):
    self.menu = '''\nMenu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''

    getNameFromUser(self):
        self.yourName = raw_input('What is your name? ')

        displayMenu(self):
            while True:
                print self.menu
                input = raw_input("")
                if input.upper() == "V":
                    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":
                                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. "

                                    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()

                                                        saveScore(self):
                                                            print "\nWould you like to save your score? (Y)es or (N)o:"
                                                            inp = raw_input().upper();
                                                            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

                                                            main():
                                                                game = GuessingGame() #Constructing the game
                                                                game.getNameFromUser()
                                                                game.displayMenu() #runs the menu, which then has all the options

                                                                if __name__ == "__main__":
                                                                    main()

The problem is that when it is run, I get syntax and indentation errors from Python IDLE. Also the second code may look terrible (and I believe it is), but that is how python decided to indent it. The top code is fine and doesn't need work, the second code is where I am stumped. I need it to work without and functions, classes or methods like the first. Unless methods have to be used.

Recommended Answers

All 8 Replies

You have not function definations in second version, you have else instead of elif in some conditions and you have not taken out the self parameters.

I know there are no function definitions in the second version of the code as I am trying to do the same thing minus definitions. So by replacing else with elif in some conditions (which ones?) and removing the self parameters then in theory it should work?

Considering that you 91 lines and I have round 20 (minus Python3 check) in http://www.daniweb.com/code/snippet287950.html, you should consider some additional clean up also (I also do error check of number input).

This is how you define regular functions:

def func(a,b):
    return a+b

a,b=23,45
print func(a, b)

I know how to define functions as that is what I was taught, I just don't really get writing code without them, seems backwards to me. Where using functions, methods, classes, etc are a logical step and should be done like that from the start.

import random
from operator import itemgetter

isint(x)
try:
    int(x)
    return True
except:
    return False
print "Invalid guess. "

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

__init__():
    menu = '''\nMenu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''

    getNameFromUser():
        yourName = raw_input('What is your name? ')

        displayMenu():
            while True:
                print menu
                input = raw_input("")
                if input.upper() == "V":
                    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":
                                gameMode() #using self. to call method from inside the class - which doesn't apply when a class is not used
                                elif input.upper() == "Q":
                                    print "Thank you for playing. "
                                    return
                                else:
                                    print "Invalid menu choice. "

                                    gameMode():
                                        number = random.randint(1, 42)
                                        guess = -1
                                        guessesTaken = 0

                                        while guess != number:
                                            guess = getGuessValidator()
                                            if guess < number:
                                                print 'My number is higher.'
                                                elif guess > number:
                                                    print 'My number is lower.'
                                                    guessesTaken += 1

                                                    if guess == number:
                                                        print 'Good job, ' + yourName + '! You guessed my number in',guessesTaken,'guesses!'
                                                        saveScore()

                                                        saveScore():
                                                            print "\nWould you like to save your score? (Y)es or (N)o:"
                                                            inp = raw_input().upper();
                                                            if inp == "Y":
                                                                saveStr = yourName + ', ' + str(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

                                                            main():
                                                                game = GuessingGame() #Constructing the game
                                                                game.getNameFromUser()
                                                                game.displayMenu() #runs the menu, which then has all the options

                                                                if __name__ == "__main__":
                                                                    main()

The self parameters have being removed and now I get syntax errors where there are : and when they are removed I get indentation errors, which doesn't fix anything.

you are missing def.

Then see my code snippet, it has no functions. Add any extra functionality or exchange your code instead of mine. You must put the function definition code inline where they are called replacing parameter names with actual calling values.

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.