-2

ok so i would like it that when the user wants to check the high scores the output would print the data in descending order keep in mind that there are both names and numbers on the .txt file which is why im finding this so hard. If there is anything else you need please tell me in the

def highscore():
        global line #sets global variable
        for line in open('score.txt'):
            print(line)
    #=================================================================================
    def new_highscores():
        global name, f #sets global variables
        if score >= 1:#if score is equal or more than 1 run code below
            name = input('what is your name? ')
            f = open ('score.txt', 'a') #opens score.txt file and put it into append mode
            f.write (str(name)) #write name on .txt file
            f.write (' - ') #write - on .txt file
            f.write (str(score)) #write score on .txt file
            f.write ('\n') #signifies end of line
            f.close() #closes .txtfile
        if score <= 0: #if score is equal to zero go back to menu 2
            menu2() 

I added this just in case there was a problem in the way i was writing on the file

DSM
  • 291,791
  • 56
  • 521
  • 443
  • how do you run it, do you call those functions from anywhere? – davedwards May 06 '17 at 05:57
  • yes i can add the full code if you would like – Jesuspepper May 06 '17 at 08:26
  • @Jesuspepper have you taken a look at my answer? If you have further questions about it or it's not working, please add a comment to it, but I think it should do what you need. – Jon McClung May 06 '17 at 13:54
  • @JonMcClung i get this error saying name is not defined File "C:\Python34\rock paper scissors 1.7.py", line 229, in highscore scores.append((score, name)) NameError: name 'name' is not defined also what do the underscores mean? – Jesuspepper May 07 '17 at 00:59
  • I don't think you understand the code I gave you. Did you read everything? It was intended to go inside of your `new_highscores` method. I'll update it so that it's more clear. As a general rule, though, you shouldn't just copy/paste code you don't understand. – Jon McClung May 07 '17 at 01:12
  • @Jesuspepper if you have further issues with my answer, please comment on the answer itself, not here. – Jon McClung May 07 '17 at 01:20

1 Answers1

0

The easiest thing to do is just maintain the high scores file in a sorted state. That way every time you want to print it out, just go ahead and do it. When you add a score, sort the list again. Here's a version of new_highscores that accomplishes just that:

def new_highscores():
    """"Adds a global variable score to scores.txt after asking for name"""
    # not sure you need name and f as global variables without seeing 
    # the rest of your code. This shouldn't hurt though
    global name, f # sets global variables
    if score >= 1: # if score is equal or more than 1 run code below
        name = input('What is your name? ')

        # here is where you do the part I was talking about:
        # get the lines from the file
        with open('score.txt') as f:
            lines = f.readlines()

        scores = []
        for line in lines:
            name_, score_ = line.split(' - ')
            # turn score_ from a string to a number
            score_ = float(score_)
            # store score_ first so that we are sorting by score_ later
            scores.append((score_, name_))

        # add the data from the user
        scores.append((score, name))
        # sort the scores
        scores.sort(reverse=True)

        # erase the file
        with open('score.txt', 'w') as f:
            # write the new data
            for score_, name_ in scores:
                f.write('{} - {}\n'.format(name_, score_))        

    if score <= 0: # if score is equal to zero go back to menu 2
        menu2()

You'll notice I'm using the with statement. You can learn more about that here, but essentially it works like this:

with open(filename) as file:
    # do stuff with file
# file is **automatically** closed once you get down here. 

Even if you leave the block for another reason (an Exception is thrown, you return from a function early, etc.) Using a with statement is a safer way to deal with files, because you're basically letting Python handle the closing of the file for you. And Python will never forget like a programmer will.

You can read more about split and format here and here

P.S., There is a method called binary search that would be more efficient, but I get the feeling you're just starting so I wanted to keep it simple. Essentially what you would do is search for the location in the file where the new score should be inserted by halving the search area at each point. Then when you write back to the file, only write the stuff that's different (from the new score onward.)

Community
  • 1
  • 1
Jon McClung
  • 1,438
  • 16
  • 25
  • i have added the rest of my code if you would like to look at it as i feel that i have not provided you with everything you need. Also is there anything i need to change with def_highscore? – Jesuspepper May 07 '17 at 01:46
  • The `high_score` function should be fine. Have you updated your `new_highscores` to match mine? If you are having issues, be specific about what's not working. Furthermore, you need to understand the code I've already given. I can't help you if you're not even going to read my answer enough to understand how you're supposed to use it. – Jon McClung May 07 '17 at 01:53
  • yes i have updated it but want to go through it in more detail i will keep you posted with any problems i have with it – Jesuspepper May 07 '17 at 01:58
  • yes i wasn't talking about my whole project i was talking about the specific piece of code you gave me i just want to get to grips with it and understand it fully before i ask you for more help concerning the piece of code you gave me – Jesuspepper May 07 '17 at 02:05
  • @Jesuspepper Right, I realized that shortly after posting my comment, so I deleted it. I'm glad you're trying to understand it. – Jon McClung May 07 '17 at 02:06
  • Ok so when i run it nothing happens if i go check the high scores nothing is there. So in def_highscores i decided to change it from score.txt to scores.txt which is the only way it will produce and output if i leave it like that it will replace the data in the file each time i add new data so i changed with open('scores.txt', 'w') as f: to with open('scores.txt', 'a') as f: to put it into append mode so it adds to the data however it still doesn't put it in descending order if there is something that you think i haven't understood please pull me up on it. – Jesuspepper May 07 '17 at 03:12
  • @Jesuspepper that's my bad. It should be the same filename everywhere. Use either score.txt or scores.txt but make sure it's the same everywhere. There should be 3 different places. In that case using write mode ('w', not 'a') should make everything work as intended. – Jon McClung May 07 '17 at 03:16
  • Ok changed everything to score.txt and change it back from 'a' to 'w' there is just one small thing. When i view the high scores the last score that i entered will not have.0 on the end and all the other data will have.0 on the end peter - 5.0 james - 3 jeff - 1.0 john - 1.0 jack - 1.0 Bar - 1.0 that is the output i am getting but i want to to look more like this peter - 5.0 james - 3.0 jeff - 1.0 john - 1.0 jack - 1.0 Bar - 1.0 – Jesuspepper May 07 '17 at 03:22
  • If you want them in that format, use `'{} - {:.1f}\n'` instead of `'{} - {}\n'` – Jon McClung May 07 '17 at 03:29