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

Recommended Answers

All 8 Replies

To write out to file use ...

fileHandle = open ( 'scores.txt', 'w' )
fileHandle.write(str1)
fileHandle.close()

To append to an existig file use ...

fileHandle = open ( 'scores.txt', 'a' )
fileHandle.write(str1)
fileHandle.close()
commented: did not know about the append function for text files. Thanks! +1

Thanks for the response vegaseat, I knew of the default if left blank (which is read), read (r) and write (w). I will put it into my code, test it out and post back here once that is done.

if guess == number:
            print 'Good job, ' + self.yourName + '! You guessed my number in',self.guessesTaken,'guesses!'

            print "\nWould you like to save your score? (Y)es or (N)o:"
            
    def saveScore(self):
        input = raw_input("");
        if input.upper() == "Y":
            while input.upper() == "Y":
                fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt 
                fileHandle.write(str1)
                fileHandle.close()
                print str1
                break
        elif input.upper() == "N":
            return
        else:
            print "Choose either (Y) or (N)o. "

This is the final part before the loop where I need it to append to the txt file. I think I have messed up the code that allows the user to either save (Yes) or not (No) their score. Will work on it more and check back later and figure out how to make it so it sorts it in correct order (lowest to highest guess) or leave it as is in reverse order, it would be nice to sort them in the correct order as I said before, but the user can still see the high scores.

Sorry for the double post, but I could not edit the previous post.

This snippet is the final piece before the main loop, I don't need to worry about it displaying the scores after saving. That is what (V) is for in the menu. I am still stumped on getting it to save to the text file after the user inputs (Y)es. Let me know how close I am to getting it to work properly.

if guess == number:
            print 'Good job, ' + self.yourName + '! You guessed my number in',self.guessesTaken,'guesses!'

            print "\nWould you like to save your score? (Y)es or (N)o:"
            
    def saveScore(self):
        input = raw_input("");
        if input.upper() == "Y":
            while input.upper() == "Y":
                fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt 
                fileHandle.write(str1)
                fileHandle.close()
                print str1
                break
        elif input.upper() == "N":
            return
        else:
            print "Choose either (Y) or (N)o. "

Two things stick out, the while loop is not needed and don't use Python function names like input as variable names ...

def saveScore(self):
        inp = raw_input().upper();
        if inp == "Y":
            #the use of 'a' will append the score to the scores.txt 
            fileHandle = open ( 'scores.txt', 'a' ) 
            fileHandle.write(str1)
            fileHandle.close()
            #print str1
            return
        elif inp == "N":
            return
        else:
            print "Choose either (Y) or (N)o. "
            self.saveScore()

ok that makes sense, here is the full code which works. Just need to get it so when the user enters Y or Yes it will append to the text file. Which I will have a tinker with.

#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 = '''\nMenu:\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!'

            print "\nWould you like to save your score? (Y)es or (N)o:"
            
    def saveScore(self):
        inp = raw_input().upper();
        if inp == "Y":
            fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt
            fileHandle.write(str1)
            fileHandle.close()
            print "Saving high scores file... "
            return
        elif inp == "N":
            return
        else:
            print "Choose either (Y) or (N)o. "
            self.saveScore()

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 second while/break statements in displayMenu() does nothing. You can delete them. And just use another function to write to the file.

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

    def to_file(self):
        print "\nWould you like to save your score? (Y)es or (N)o:"
        save_it = raw_input()
        if save_it.upper() in ["Y", "Yes"]:
           fp = open(fname, "w")
           fp.write(all_the_stuff)
           fp.close()

I was told I needed them in there, oh well if they are not needed then may as well remove them.

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.