0

I have created a simple command line game in python. The user begins by inputting their nickname which is stored as name

At the end of the game the user's score is stored in a file like so:

wins = str(wins)
losses = str(losses)

file = open('scores.py','a')
file.write(name + ": wins = " + wins + "  losses = " + losses + "\n\n")
file.close

( I converted the 'wins' and 'losses' variables to strings as I couldn't seem to write integers to a file, I don't know if this is possible (i'm sure it is) but I just didn't know how to do it. )

I want the user playing the game to have a cumulative score, i.e. if they were to play 1 game and win 6 rounds, play another game and win 2 rounds, I don't want there to by 2 entries in the 'scores.py' file, I would like it to say:

*User*: wins = 8 losses = 0

The only way I could think of doing this is that after each game finishes, the user's name and score would be appended to the 'scores.py' file, but before that, the file is scanned line-by-line to check whether or not the user's nickname already has an entered score. IF the name inputted at the start of the game is the same name as the one being read on the particular line in the 'scores.py' file, extract the line, convert the string values for wins and for losses to integers, add the current score in the game to the stored score, and then write it back into the file.

Any and all help would be greatly appreciated, and excuse me if the code is terrible and the solution is simple, I am extremely new to python and am not very well-versed in code in general either.

Will
  • 3
  • 3
  • Don't use the `.py` extension unless the content is valid python. It's too confusing. – Peter Wood Apr 02 '17 at 00:51
  • 1
    Possible duplicate of [Is it possible to modify lines in a file in-place?](http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – Peter Wood Apr 02 '17 at 00:52
  • 1
    You could use a dictionary ```{'user':[wins, losses], ...}``` to hold the info for all your users then use [pickle](https://docs.python.org/3/library/pickle.html#module-pickle) to serialize the dictionary. – wwii Apr 02 '17 at 02:04
  • You should try to implement your idea then come back here, if you get stuck on something, and ask a question. – wwii Apr 02 '17 at 02:09

1 Answers1

0

You can use the built-in json module. I think it fits nicely with your use case.

import json

def update_scores(name, wins, losses, scores_file='scores.json'):
    try:
        with open(scores_file, 'r') as f:
            scores = json.load(f)
    except (IOError, ValueError):
        # Non existing or empty file.
        scores = {} 
    try:
        scores[name]['wins'] += wins
        scores[name]['losses'] += losses
    except KeyError:
        # Initialize user score
        scores[name] = {'wins': wins, 'losses': losses}
    with open(scores_file, 'w') as f:
        json.dump(scores, f)

# Use:
update_scores('foo', 3, 8)  # {"foo": {"wins": 3, "losses": 8}}
update_scores('foo', 3, 2)  # {"foo": {"wins": 6, "losses": 10}}
update_scores('bar', 8, 0)  # {"foo": {"wins": 6, "losses": 10}, "bar": {"wins": 8, "losses": 0}}
feqwix
  • 1,362
  • 14
  • 16
  • I tried implementing this and it didn't seem to do anything at all. There were no errors, no entries in the scores file, nothing. – Will Apr 02 '17 at 17:57
  • Scrap that! The code seems to work great for now, I shall try to error check it and experiment with it some more, but for now it works perfectly. Thank you very much! – Will Apr 02 '17 at 18:05