Python and Highscore.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cromoglic
    New Member
    • Mar 2008
    • 13

    Python and Highscore.

    Hello! I have been making a "guess what number the computer thinks of"-game in python (text-only) for educational reasons. Now, i want to implement a highscore in the code, which writes the best three players with names and number of attempts. First, I'll just show you my game, but nevermind the code in that one:

    Code:
    #Importere modulen random: 
    import random
    #thenumber tilsvarer nå random.randint(0, 100) som er et tilfeldig tall mellom 0 og 100)
    thenumber = random.randint(0, 100)
    # Et tappert forsøk på en loop.
    loop = 1
    
    #Definerer choice.
    choice = 0
    forsøk = 0
    
    #Så til selve gjettedelen av scriptet :)
    
    print "It is a number between 0 and 100. Can you guess it?" 
    print "Guess-the-number-game made by CromogliC"
    print "Just type in a number of your own choice and press enter!"
    
    yourname = raw_input("Please type in your name here: ") 
    
    while loop == 1:
        choice = input("What number do you think is is?: ")
        if choice == thenumber:
            forsøk = forsøk +1
            print "Amazing," + " " + yourname + "!"
            print "You have guessed the right number!"
            print "You are victorious!"
            print "Tries used:"
            print forsøk
            wins = forsøk
            loop = 0
            print "Restart? y for yes. n for no."
            restart = raw_input("Do you want to restart?: ")
            if restart == "y":
                forsøk = 0
                #User restart!
                loop = 1
            elif restart == "n":
                loop = 0
                print "Game Over!"
                exit()
        elif choice < thenumber:
            print "Nope, you have got to go higher!"
            forsøk = forsøk +1
            loop = 1
        elif choice > thenumber:
            print "Nope, you have got to go lower!"
            forsøk = forsøk +1
            loop = 1
        elif choice > 100:
            print "I am sorry, but you cannot pick a number above 100!"
            loop = 1
    Explanation: The notes are just explaining what the different sections does. nevermind those at all - they are in norwegian because i am a norwegian^^
    Forsøk (in english attempts/tries) indicates how many attempts the user have used on guessing the right number. I did not plan on getting a highscore for this game, but now I've changed my mind. However, the integration of the actual highscore-code might be a little harder then. (Am I right?:P)

    Now, to the actual highscore-code. I found a highscore from a previous post in here, but I am rather new to Python, and therefore had some trouble using it. Well, here is it (a little bit modifyed, as i tried to make it work on my own):

    Code:
    def hasHighScore(score):
    #opens guessnumberhighscore.txt
        infile = open("guessnumberhighscore.txt",'r')
        scores = [0,0,0]
        names = ["","",""]
    
    #reads in scores from guessnumberhighscore.txt
    i=0
    for line in infile.readlines():
        scores[i],names[i] = string.split(line,"\t")
        names[i]=string.rstrip(names[i])
        i += 1
        infile.close()
    
    #compares player's score with those in guessnumberhighscore.txt
    i=0
    for i in range(0,len(scores)):
        if(score in(scores[i])):
            return True
        else:
            return False
    
    def setHighScores(score,name):
    #opens guessnumberhighscore.txt
        infile = open("guessnumberhighscore.txt",'r')
        scores = [0,0,0]
        names = ["","",""]
    
    scores = [0,0,0]
    #reads in scores from guessnumberhighscore.txt
    i=0
    for line in infile.readlines():
        scores[i],names[i] = string.split(line,"\t")
        scores[i]=int(scores[i])
        names[i]=string.rstrip(names[i])
        i += 1
        infile.close()
    
    #shuffles thru the guessnumberhighscore.txt and inserts player's score if
    #higher than those in file
    i=len(scores)
    while(score == scores[i-1] and i>0):
        i -= 1
    scores.insert(i,score)
    names.insert(i,name)
    scores.pop(len(scores)-1)
    names.pop(len(names)-1)
    
    #writes new guessnumberhighscore.txt
    outfile = open("guessnumberhighscore.txt","w")
    
    outfile.write (" High Score Name \n")
    outfile.write ("-------------------------------------------------\n")
    
    i=0
    for i in range(0,len(scores)):
        outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
        outfile.close()
    
    
    #adds player's score to high score list if high enough
    if(hasHighScore(wins) == True):
        setHighScores(wins,yourname(wins))
    Can anyone help me out a little?;)
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    [CODE=python]
    def readHighScores( ):
    #opens guesshighscores .txt
    infile = open("guesshigh scores.txt",'r' )
    scores = [0,0,0]
    names = ["","",""]

    #reads in scores from guesshighscores .txt
    for idx, line in enumerate(infil e):
    scores[idx],names[idx] = tuple(line.stri p().split())
    infile.close()

    return scores, names


    def hasHighScore(sc ore):
    #opens guesshighscores .txt
    scores, names = readHighScores( )

    #compares player's score with those in guesshighscores .txt
    for elem in scores:
    if int(score) < int(elem):
    return True
    return False

    def setHighScores(s core, name):
    #opens guesshighscores .txt
    scores, names = readHighScores( )

    # re-writes the list of highscores
    for idx, elem in enumerate(score s):
    if score > elem:
    continue
    scores.insert(i dx, score)
    names.insert(id x, name)
    scores.pop()
    names.pop()
    break

    #writes new guesshighscores .txt
    outfile = open("guesshigh scores.txt","w" )

    i=0
    for i in range(0,len(sco res)):
    outfile.write(" \t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
    outfile.close()
    outfile = open('guesshigh scores.txt', 'r')
    print outfile.read()
    outfile.close()
    [/CODE]
    What was it that gave you trouble? I've posted some general fixes above (just a few things I noticed off the bat). But please let us know how you were having trouble.. was it syntax errors? Just wasn't doing what was expected? Elaborate...

    Comment

    • cromoglic
      New Member
      • Mar 2008
      • 13

      #3
      Thank you:) Well, first of all i need a variable that writes to file after each successfully ended game. How do I do this? Can I just modify the game script, renaming all my score and name variables so they match with the variables for score and names in the HighScore code?


      About the code: Yeah, last time i got some syntax errors (blocks and stuff, which I fixed easily, and one syntax error for "while score scores[i-1] and...", cant remember the exact error, but it was a syntax error caused by the word "scores". Might have been "scores is not defined", although one of the first lines defines scres by: scores = [0,0,0]. Anyways, your fixes seems to have fixed the problem.

      Comment

      • jlm699
        Contributor
        • Jul 2007
        • 314

        #4
        Originally posted by cromoglic
        Can I just modify the game script, renaming all my score and name variables so they match with the variables for score and names in the HighScore code?
        Not necessary, since the high score code is all functions. As long as you're passing the correct values, you will achieve the desired result

        Comment

        • cromoglic
          New Member
          • Mar 2008
          • 13

          #5
          Hmm. My problem, at the moment, is making the highscore-code to read from my game-code. I'll post all of it here:

          Code:
           
          #Importere modulen random: 
          import random
          #thenumber tilsvarer nå random.randint(0, 100) som er et tilfeldig tall mellom 0 og 100)
          thenumber = random.randint(0, 100)
          # Et tappert forsøk på en loop.
          loop = 1
          
          #Definerer choice.
          choice = 0
          forsøk = 0
          
          #Så til selve gjettedelen av scriptet :)
          
          print "It is a number between 0 and 100. Can you guess it?" 
          print "Guess-the-number-game made by CromogliC"
          print "Just type in a number of your own choice and press enter!"
          
          yourname = raw_input("Please type in your name here: ") 
          
          while loop == 1:
              choice = input("What number do you think is is?: ")
              if choice == thenumber:
                  forsøk = forsøk +1
                  print "Amazing," + " " + yourname + "!"
                  print "You have guessed the right number!"
                  print "You are victorious!"
                  print "Tries used:"
                  print forsøk
                  wins = forsøk
                  loop = 0
                  print "Restart? y for yes. n for no."
                  restart = raw_input("Do you want to restart?: ")
                  if restart == "y":
                      thenumber = random.randint(0, 100)
                      forsøk = 0
                      #User restart!
                      loop = 1
                  elif restart == "n":
                      loop = 0
                      print "Game Over!"
                      exit()
              elif choice < thenumber:
                  print "Nope, you have got to go higher!"
                  forsøk = forsøk +1
                  loop = 1
              elif choice > thenumber:
                  print "Nope, you have got to go lower!"
                  forsøk = forsøk +1
                  loop = 1
              elif choice > 100:
                  print "I am sorry, but you cannot pick a number above 100!"
                  loop = 1
          
          def readHighScores():
              #opens guesshighscores.txt
              infile = open("guesshighscores.txt",'r')
              scores = [0,0,0]
              names = ["","",""]
           
              #reads in scores from guesshighscores.txt
              for idx, line in enumerate(infile):
                  scores[idx],names[idx] = tuple(line.strip().split())
              infile.close()
           
              return scores, names
           
           
          def hasHighScore(score):
              #opens guesshighscores.txt
              scores, names = readHighScores()
           
              #compares player's score with those in guesshighscores.txt
              for elem in scores:
                  if int(score) < int(elem):
                      return True
              return False
           
          def setHighScores(score, name):
              #opens guesshighscores.txt
              scores, names = readHighScores()
           
              # re-writes the list of highscores
              for idx, elem in enumerate(scores):
                  if score > elem:
                      continue
                  scores.insert(idx, score)
                  names.insert(idx, name)
                  scores.pop()
                  names.pop()
                  break
           
              #writes new guesshighscores.txt
              outfile = open("guesshighscores.txt","w")
           
              i=0
              for i in range(0,len(scores)):
                  outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
              outfile.close()
              outfile = open('guesshighscores.txt', 'r')
              print outfile.read()
              outfile.close()

          Comment

          • jlm699
            Contributor
            • Jul 2007
            • 314

            #6
            Well what do you mean read from your code? You never call any of the highschore functions, so obviously nothing is going to happen. Basically all you need to do is check if the player's score is the high score when they win. If it returns true then call the set high score function with their name and score.

            Comment

            • cromoglic
              New Member
              • Mar 2008
              • 13

              #7
              so if i add something similiar to
              while forsøk < 0:

              and then the highscore-code it should work? Then, it will check the txt-file as long as my result is greater than 0

              Comment

              • jlm699
                Contributor
                • Jul 2007
                • 314

                #8
                No. Do you know what calling a function is?
                You would want something more like this (which is when you have determined the player has won...):
                [code=python]
                forsøk = forsøk +1
                print "Amazing," + " " + yourname + "!"
                print "You have guessed the right number!"
                print "You are victorious!"
                print "Tries used:", forsøk
                wins = forsøk
                if hasHighScore(wi ns):
                setHighScores(w ins, yourname)
                [/code]

                Comment

                • cromoglic
                  New Member
                  • Mar 2008
                  • 13

                  #9
                  Hmm, I thought "commands" such as "if" and "while" etc. were calling commands. Bare in mind that I started with python a week ago:P I will try your suggestion, thank you:)

                  Comment

                  • cromoglic
                    New Member
                    • Mar 2008
                    • 13

                    #10
                    Well, i tried to add the code you gave me, with the result of setHighScores etc. not being defined - easy enough, I just put the highscorepart over the actual game-part. Now, i get this error when I've guessed the right number:

                    Traceback (most recent call last):
                    File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 82, in ?
                    if hasHighScore(wi ns):
                    File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 29, in hasHighScore
                    scores, names = readHighScores( )
                    File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 15, in readHighScores
                    infile = open("guesshigh scores.txt",'r' )
                    IOError: [Errno 2] No such file or directory: 'guesshighscore s.txt'

                    The highscorecode is supposed to write a new guesshighscores .txt, but as it didnt, I made a textfile with that name manually. The error persists. I found out that I had called the file i made guesshighscores .txt, which results in the full name: guesshighscores .txt.txt (as the file extension is added). When I fixed this, the "game" runs without errors, but it doesnt write anything to my file. It seems like the call-function or the highscore-codepart does not work properly/isnt configured properly, but I cant see whats wrong. Help me?:D

                    Comment

                    • jlm699
                      Contributor
                      • Jul 2007
                      • 314

                      #11
                      It would seem to me that if the file is empty, then the hasHighScore function will never have anything to compare the score to; thereby never being able to return True.

                      In your txt file make entries with a score of 100 and a random name like CPU1, 2 and 3 or similar.

                      Similarly, if you're looking to learn good programming practices, at the initialization of your program you could do the following:
                      [code=python]
                      import os

                      if not os.path.exists( 'guesshighscore s.txt'):
                      fh = open('guesshigh scores.txt', 'w')
                      fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')
                      fh.close()
                      [/code]
                      That way you can be sure that you won't get a file does not exist error, as well as there being default scores... HTH

                      Comment

                      • cromoglic
                        New Member
                        • Mar 2008
                        • 13

                        #12
                        Thank you, you have been really helpful :)
                        Could you explain the bit about CPU/n? I did not understand that part:P (just for learning)

                        Comment

                        • cromoglic
                          New Member
                          • Mar 2008
                          • 13

                          #13
                          Oh, by the way, the code prevents errors from appearing, but the program still wont write to file.

                          Comment

                          • jlm699
                            Contributor
                            • Jul 2007
                            • 314

                            #14
                            \n is what's known as an escape character... any character that has a \ in front of it is an escape character (\n is the escape character for "new line".. so it's like pressing enter in a text editor... it creates a "new line").
                            [code=python]
                            fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')
                            [/code]
                            is simply shorter than writing
                            [code=python]
                            fh.write('100 CPU1\n')
                            fh.write('100 CPU2\n')
                            fh.write('100 CPU3\n')
                            [/code]
                            So when you say it's not writing to file .. are you sure you're checking the correct file? Does it print out the correct high scores ? I'm thinking that the file is in a different location than where you imagine it to be. A quick " print os.getcwd() " at the beginning of your program will tell you the current working directory, which is where the highscore file is being read/written

                            Comment

                            • cromoglic
                              New Member
                              • Mar 2008
                              • 13

                              #15
                              Yes, I've learnt that the working directory usually is where the actual script is saved. To be sure, i tried your command, which proved that i was right about the directory. However, when i tried to delete the txt-file i manually created earlier, it worked. Now, it looks damn messy, so I'll start working on the "layout" now;) Thank you alot for your help:)!

                              By the way, will I be able to make line at the top containing for instance PlayersName Score

                              which will stand the "for ever" by adding a /n at the beginning of the fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')-line?



                              now, I am starting to get this error:

                              Traceback (most recent call last):
                              File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 92, in ?
                              if hasHighScore(wi ns):
                              File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 39, in hasHighScore
                              scores, names = readHighScores( )
                              File "C:\Documen ts and Settings\Omni Potent\Desktop\ Python scripting\Guess numbergame\gues snumber.py", line 31, in readHighScores
                              scores[idx],names[idx] = tuple(line.stri p().split())
                              ValueError: too many values to unpack

                              Even though i didnt touch anything:P For me, it seems like this occurs every time my score is above 9, but I could be wrong:P

                              Comment

                              Working...