Hi.. I've been trying to get this to work for hours now but I'm not understanding what to do.

Basically I'm creating a quiz on python with 5 questions.
I have a function that is only for the quiz.
Another function is to display the highest quiz score.
I want to keep the highest score in a text file that the program can read from and write to.

Here's the pseudo code for what I want to do:

- take quiz
- calculate score
- read highScore.txt
-- determine if new high score is greater than the high score in the text file.
----if yes: replace high score in text file with the next high score just received.
----if not: leave the text file as is

So far, I'm getting the program to just read what the text file says.
How do I assign a variable to the high score in the text file?

For example:

(Text File): oldScore
if newScore > oldScore, then write newScore to file
if newScore < oldScore, do nothing.

I'm not sure if I'm making sense, but I'm a newbie and just confused at this point.
Any help would be greatly appreciated!

Dani AI

Generated

Good instincts, . Two things are tripping you up: you are comparing a string read from disk to an int, and you are trying to write to a handle opened in read-only mode. Also, if playerL is a list, printing it will show a Python list repr; convert it to a string before saving.

A simple, robust pattern is to separate concerns:

  • update the high score immediately after a game ends
  • display the high score from the menu without recalculating anything

Storing name+score as JSON avoids fragile string splitting (building on ’s separator idea) and makes parsing safer.

import json
import os

PATH = 'score.json'

def read_highscore(path=PATH):
    try:
        with open(path, 'r') as f:
            data = json.load(f)
            return data.get('name', ''), int(data.get('score', 0))
    except (IOError, ValueError, TypeError):
        return '', 0  # default when file is missing/corrupt

def update_highscore(name, score, path=PATH):
    _, best = read_highscore(path)
    score = int(score)
    if score > best:
        with open(path, 'w') as f:
            json.dump({'name': str(name), 'score': score}, f)
        return True
    return False

# after the quiz ends:
# player_name = ' '.join(playerL) if playerL is a list
# total = sum(points)
# updated = update_highscore(player_name, total)

# from the menu "HIGH SCORE":
# name, best = read_highscore()
# print(name, best)

Troubleshooting:

  • Always cast file values to int before comparing.
  • Close the read handle before opening for write (the with blocks above handle this).
  • If you keep a plain text file, at minimum do old = int(open(...).read().strip() or 0) and ensure you reopen with mode 'w' only after you have decided to update.

Recommended Answers

All 8 Replies

And the code?

I can't see it. lol

:)

f_score = open ('score.txt')
old_score = int(f_score.readlines()[0])
f_score.close()
score = 80
print old_score
if score > old_score:
    f_score = open ('score.txt', 'w')
    f_score.write('%s' % score)
    f_score.close()

This is what I've been trying to work with, but it just keeps printing out whatever is on the file.

def highscore():
    newScore = sum(points)
    print
    openHigh = open("highScore.txt", 'r')
    highScore = openHigh.read()
    print highScore
    print newScore

    if newScore > highScore:
        openHigh.write(newScore)
        openHigh.close()
        print highScore

Also, what if I would like to display the person's name? How would I go about adding the person's name AND score, but only reading the score to see if the file should be updated with the new person's name and score?

See my example.

Write the name and the socre with some separator.

Then do some spliting on reading, and compare only the last field.

Here.

score.txt content before:

Jane-60
f_score = open ('score.txt')
old_highscore = f_score.readlines()[0]
f_score.close()
old_name, old_score = old_highscore.split('-')
name = 'Joe'
score = 80
print old_name, old_score
if score > int(old_score):
    print name, score
    f_score = open ('score.txt', 'w')
    f_score.write('%s-%s' % (name, score))
    f_score.close()

score.txt content after:

Joe-80

This is what I've been trying to work with, but it just keeps printing out whatever is on the file.

def highscore():
    newScore = sum(points)
    print
    openHigh = open("highScore.txt", 'r')
    highScore = openHigh.read()
    print highScore
    print newScore

    if newScore > highScore:
        openHigh.write(newScore)
        openHigh.close()
        print highScore

You have the file open as reading mode. Thats why.

openHigh = open("highScore.txt", [B]'r'[/B])

I'm not sure what's happening... It only keep showing me the old_name and old_score from the score.txt file.

def highscore():

    print
    print "=" * 75
    print "                                 HIGH SCORE"
    print
    print

    newScore = sum(points)
    newPlayer = playerL[:]
    
       
    f_score = open('score.txt')
    old_highscore = f_score.readlines()[0]
    f_score.close()
    old_name, old_score = old_highscore.split('-')

    if newScore > int(old_score):
        print newPlayer, newScore
        f_score = open('score.txt', 'w')
        f_score.write('%s-%s' % (newPlayer,newScore))
        f_score.close()

    elif newScore <= int(old_score):
        print old_name, old_score

And this is what it's keeps outputting everytime:

***************************
                      ***************************

                              GAME OVER

                          You won $ 23000 !!!

                      ***************************
                      ***************************

Play Again? 1=Yes 2=No :  2

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                          WHO WANTS TO BE A MILLIONARE? 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1)   PLAY GAME

2)   INSTRUCTIONS

3)   HIGH SCORE

4)   EXIT

Please enter a selection (1-4):  3

===========================================================================
                                 HIGH SCORE


player 1000



Press 1 to continue:

One question.

When the player looses, how are you saving the highscore?

In your example you show a player that played and then you call the highscore from the menu.

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.