By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,270 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,270 IT Pros & Developers. It's quick & easy.

Highscore

P: 24
Hi! I want to make a highscore for a game i am making. How might i do that?

Thanks
Nov 25 '06 #1
Share this Question
Share on Google+
30 Replies


bartonc
Expert 5K+
P: 6,596
Hi! I want to make a highscore for a game i am making. How might i do that?

Thanks
You might do that many ways. Tell us more about what "make a high score" means (do you mean make a way to remember the top 5 high scores over time?).
Nov 25 '06 #2

P: 24
Yes.... I mean.... i want to make my program save the top 10 scores and names in some way....
Nov 25 '06 #3

bartonc
Expert 5K+
P: 6,596
Yes.... I mean.... i want to make my program save the top 10 scores and names in some way....
Here, I use a list of tuples. This list can be sorted by score, then pickled to save it to disk. Pickle documentation is in section 3.14.3 of python 2.4 docs.

>>> hiscores = [(300, "John")]
>>> score = 200
>>> player = "Jane"
>>> hiscores.append((score, player))
>>> print hiscores
[(300, 'John'), (200, 'Jane')]
>>> hiscores.sort()
>>> print hiscores
[(200, 'Jane'), (300, 'John')]


>>> import pickle

>>> scores = open("scores", "w")
>>> pickle.dump(hiscores[-10:], scores)
>>> scores.close()

>>> scores = open("scores", "r")
>>> oldscores = pickle.load(scores)
>>> scores.close()
>>> print oldscores
[(200, 'Jane'), (300, 'John')]
>>>
Nov 26 '06 #4

P: 24
Thanks! What does pickle do?
Nov 26 '06 #5

P: 24
OK.... i think i get it now... thanks
Nov 26 '06 #6

P: 24
How would you do it if you used a lists? Like:
score=list()
name=list()

in some way?
Nov 26 '06 #7

bartonc
Expert 5K+
P: 6,596
Thanks! What does pickle do?
Like the name suggests, it preserves you data for later (on the disk).
Nov 26 '06 #8

bartonc
Expert 5K+
P: 6,596
How would you do it if you used a lists? Like:
score=list()
name=list()

in some way?
Yes;
these are the same:
score = [] # an empty list
score = list() # list constructor called with no arguments
Nov 26 '06 #9

P: 24
Here, I use a list of tuples. This list can be sorted by score, then pickled to save it to disk. Pickle documentation is in section 3.14.3 of python 2.4 docs.

>>> hiscores = [(300, "John")]
>>> score = 200
>>> player = "Jane"
>>> hiscores.append((score, player))
>>> print hiscores
[(300, 'John'), (200, 'Jane')]
>>> hiscores.sort()
>>> print hiscores
[(200, 'Jane'), (300, 'John')]


>>> import pickle

>>> scores = open("scores", "w")
>>> pickle.dump(hiscores[-10:], scores)
>>> scores.close()

>>> scores = open("scores", "r")
>>> oldscores = pickle.load(scores)
>>> scores.close()
>>> print oldscores
[(200, 'Jane'), (300, 'John')]
>>>


I tried this code... I created at textfile, called "score.txt" next to my program, and i changed score and player to raw_inputs. But if i run it a second time, the information from previous time isn't saved.
Nov 26 '06 #10

P: 24
This is the code:

hiscores = [(300, "John")]
score=raw_input("Score?")
player=raw_input("Name?")
hiscores.append((score, player))
print hiscores

hiscores.sort()
print hiscores



import pickle

scores=open("scores", "w")
pickle.dump(hiscores[-10:], scores)
scores.close()

scores = open("scores", "r")
oldscores = pickle.load(scores)
scores.close()
print oldscores




For some reason this doesn't work.
Nov 26 '06 #11

bartonc
Expert 5K+
P: 6,596
This is the code:

For some reason this doesn't work.
Hi, Max. Will you post all of you code please. Only this time, read "Posting Guidelines" in the panel on the right (while you are posting) or in the very first thread on this forum to learn how to USE CODE TAGS so that you post looks like this:


Expand|Select|Wrap|Line Numbers
  1. hiscores = [(300, "John")]
  2. score=raw_input("Score?")
  3. player=raw_input("Name?")
  4. hiscores.append((score, player))
  5. print hiscores
  6.  
  7. hiscores.sort()
  8. print hiscores
  9.  
  10.  
  11.  
  12. import pickle
  13.  
  14. scores=open("scores", "w")
  15. pickle.dump(hiscores[-10:], scores)
  16. scores.close()
  17.  
  18. scores = open("scores", "r")
  19. oldscores = pickle.load(scores)
  20. scores.close()
  21. print oldscores
Thank you,
Barton
Nov 26 '06 #12

P: 24
Actually that was all of my code... I just want that part of the program to work, then i'm gonna put it in my big program, the game i am making...

But this is my code:

Expand|Select|Wrap|Line Numbers
  1. hiscores = [(300, "John")]
  2. score=raw_input("Score?")
  3. player=raw_input("Name?")
  4. hiscores.append((score, player))
  5. print hiscores
  6.  
  7. hiscores.sort()
  8. print hiscores
  9.  
  10.  
  11.  
  12. import pickle
  13.  
  14. scores=open("scores", "w")
  15. pickle.dump(hiscores[-10:], scores)
  16. scores.close()
  17.  
  18. scores = open("scores", "r")
  19. oldscores = pickle.load(scores)
  20. scores.close()
  21. print oldscores
  22.  

It is almost the same code you wrote. I just changed in the beginning. The problem is that this doesn't work... and i don't understand why...

Thank you very much for you help!

/Max
Nov 26 '06 #13

bartonc
Expert 5K+
P: 6,596
Thanks for learning to use code tags! This helps a lot. Now I see what you have done because I only look at code in code tags.
What you need to do AFTER you have your pickle file is READ it first.


Expand|Select|Wrap|Line Numbers
  1. import pickle
  2.  
  3. scores = open("scores", "r")
  4. # READ the pickled data then add to it.
  5. hiscores = pickle.load(scores)
  6. scores.close()
  7. print hiscores
  8.  
  9. # Use int() to get a number from raw_input()
  10. score=int(raw_input("Score?"))
  11.  
  12. player=raw_input("Name?")
  13. hiscores.append((score, player))
  14. print hiscores
  15.  
  16. hiscores.sort()
  17. print hiscores
  18.  
  19. scores=open("scores", "w")
  20. pickle.dump(hiscores[-10:], scores)
  21. scores.close()
  22.  
  23. scores = open("scores", "r")
  24. oldscores = pickle.load(scores)
  25. scores.close()
  26. print oldscores
Hope that makes sense,
Barton


Actually that was all of my code... I just want that part of the program to work, then i'm gonna put it in my big program, the game i am making...

But this is my code:

It is almost the same code you wrote. I just changed in the beginning. The problem is that this doesn't work... and i don't understand why...

Thank you very much for you help!

/Max
Nov 27 '06 #14

bartonc
Expert 5K+
P: 6,596
I tried this code... I created at textfile, called "score.txt" next to my program, and i changed score and player to raw_inputs. But if i run it a second time, the information from previous time isn't saved.

The file is created by open(). Whatever name is in ("filename", "w") is the file that will be used. So if you want, you can use open("score.txt"), but the data in the file won't make much sense. The "r" and "w" are read and write mode, respectively.
Nov 27 '06 #15

P: 24
Thank you.... now it works prefectly. I inserted some extra stuff:

Score, Name, Times Played, Total time played.

I have now only one last question:

When i print this out, how do I make this look good? Now it prints out this:

(Total Score, Name, Times Played, Median Value, Total time played (sec))
(300, 'John')
(200, 'Jane')
(106, 'Bajs', 1, 106, 9)
(102, 'Hej', 1, 102, 9)
(83, 'test', 2, 41, 48)
(68.700513199546208, 'Testny', 1, 68, 14.555932021867418)
(66, 'Runk', 1, 66, 15)
(58, 'test', 1, 58, 16)
(53, 'Test4', 1, 53, 18)


Expand|Select|Wrap|Line Numbers
  1. But i would like it to print out this way:
  2.  
  3. (Total Score, Name,    Times Played, Median Value, Total time played (sec))
  4. (300             'John'      2                    142                 114)
  5. (200,            'Jane'      1                    200                 17)
  6. (106,            'Bajs',     1,                   106,                 9)
  7. (102,            'Hej',       1,                   102,                 9)
  8. (83,              'test',      2,                   41,                  48)
  9. (68.              'Testny',  1,                   68,                  14)
  10. (66,              'Runk',    1,                   66,                  15)
  11. (58,              'test',      1,                   58,                  16)
  12. (53,              'Test4',    1,                   53,                  18)
  13.  
(I did'nt know how to wright it this way here, so i used the CODE-thing. I hope you understand what i mean)

This is the code i have:

Expand|Select|Wrap|Line Numbers
  1. def highscore(totalscore, name, timesplayed, median, totaltime):
  2.  
  3.     scores = open("scores", "r")
  4.     som blir en lista
  5.     hiscores = pickle.load(scores)
  6.     scores.close()
  7.  
  8.  
  9.     hiscores.append((totalscore, name, timesplayed, median, totaltime))
  10.  
  11.     hiscores.sort    
  12.  
  13.     scores=open("scores", "w")
  14.     pickle.dump(hiscores[-10:], scores)
  15.     scores.close()
  16.  
  17.  
  18. def highscore2():
  19.     scores = open("scores", "r")
  20.     oldscores = pickle.load(scores)
  21.     scores.close()
  22.  
  23.     print "(Total Score, Name,    Times Played, Median Value, Total time played (sec))"
  24.  
  25.     for i in range(9, 0, -1):
  26.         print oldscores[i]  
  27.  
  28.  
Thanks
Nov 27 '06 #16

bartonc
Expert 5K+
P: 6,596
Thank you.... now it works prefectly. I inserted some extra stuff:

Score, Name, Times Played, Total time played.

I have now only one last question:

When i print this out, how do I make this look good? Now it prints out this:

(Total Score, Name, Times Played, Median Value, Total time played (sec))
(300, 'John')
(200, 'Jane')
(106, 'Bajs', 1, 106, 9)
(102, 'Hej', 1, 102, 9)
(83, 'test', 2, 41, 48)
(68.700513199546208, 'Testny', 1, 68, 14.555932021867418)
(66, 'Runk', 1, 66, 15)
(58, 'test', 1, 58, 16)
(53, 'Test4', 1, 53, 18)


Expand|Select|Wrap|Line Numbers
  1. But i would like it to print out this way:
  2.  
  3. (Total Score, Name,    Times Played, Median Value, Total time played (sec))
  4. (300             'John'      2                    142                 114)
  5. (200,            'Jane'      1                    200                 17)
  6. (106,            'Bajs',     1,                   106,                 9)
  7. (102,            'Hej',       1,                   102,                 9)
  8. (83,              'test',      2,                   41,                  48)
  9. (68.              'Testny',  1,                   68,                  14)
  10. (66,              'Runk',    1,                   66,                  15)
  11. (58,              'test',      1,                   58,                  16)
  12. (53,              'Test4',    1,                   53,                  18)
  13.  
(I did'nt know how to wright it this way here, so i used the CODE-thing. I hope you understand what i mean)

This is the code i have:

Expand|Select|Wrap|Line Numbers
  1. def highscore(totalscore, name, timesplayed, median, totaltime):
  2.  
  3.     scores = open("scores", "r")
  4.     som blir en lista
  5.     hiscores = pickle.load(scores)
  6.     scores.close()
  7.  
  8.  
  9.     hiscores.append((totalscore, name, timesplayed, median, totaltime))
  10.  
  11.     hiscores.sort    
  12.  
  13.     scores=open("scores", "w")
  14.     pickle.dump(hiscores[-10:], scores)
  15.     scores.close()
  16.  
  17.  
  18. def highscore2():
  19.     scores = open("scores", "r")
  20.     oldscores = pickle.load(scores)
  21.     scores.close()
  22.  
  23.     print "(Total Score, Name,    Times Played, Median Value, Total time played (sec))"
  24.  
  25.     for i in range(9, 0, -1):
  26.         print oldscores[i]  
  27.  
  28.  

Thanks
How 'bout this:

Expand|Select|Wrap|Line Numbers
  1. column_width = 18
  2.  
  3. def columnize(word, width):
  4.     nSpaces = width - len(word)
  5.     if nSpaces < 0:
  6.         nSpaces = 0
  7.     return word + (" " * nSpaces)
  8.  
  9. def highscore2():
  10.     scores = open("scores", "r")
  11.     oldscores = pickle.load(scores)
  12.     scores.close()
  13.  
  14.     header = ('Total Score', 'Name', 'Times Played', 'Median Value', 'Total time played (sec)')
  15.  
  16.     for title in header:
  17.         print columnize(title, column_width),
  18.     print
  19.     for i in range(9, 0, -1):
  20.         for col_value in oldscores[i]:
  21.             print columnize(col_value, column_width),
  22.         print
  23.  
Nov 27 '06 #17

P: 24
How 'bout this:

Expand|Select|Wrap|Line Numbers
  1. column_width = 18
  2.  
  3. def columnize(word, width):
  4.     nSpaces = width - len(word)
  5.     if nSpaces < 0:
  6.         nSpaces = 0
  7.     return word + (" " * nSpaces)
  8.  
  9. def highscore2():
  10.     scores = open("scores", "r")
  11.     oldscores = pickle.load(scores)
  12.     scores.close()
  13.  
  14.     header = ('Total Score', 'Name', 'Times Played', 'Median Value', 'Total time played (sec)')
  15.  
  16.     for title in header:
  17.         print columnize(title, column_width),
  18.     print
  19.     for i in range(9, 0, -1):
  20.         for col_value in oldscores[i]:
  21.             print columnize(col_value, column_width),
  22.         print
  23.  
It exactly what i had in mind... this doesn't work on my cpu though. Maybe col_value has to be defined or something?
Nov 28 '06 #18

P: 24
This is the Errormessage:

Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Total Score        Name               Times Played       Median Value       Total time played (sec)
  3.  
  4. Traceback (most recent call last):
  5.   File "D:\Python24\Test.py", line 25, in -toplevel-
  6.     highscore2()
  7.   File "D:\Python24\Test.py", line 22, in highscore2
  8.     print columnize(col_value, column_width),
  9.   File "D:\Python24\Test.py", line 5, in columnize
  10.     nSpaces = width - len(word)
  11. TypeError: len() of unsized object
  12.  
  13.  
Nov 28 '06 #19

bvdet
Expert Mod 2.5K+
P: 2,851
This is the Errormessage:

Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Total Score        Name               Times Played       Median Value       Total time played (sec)
  3.  
  4. Traceback (most recent call last):
  5.   File "D:\Python24\Test.py", line 25, in -toplevel-
  6.     highscore2()
  7.   File "D:\Python24\Test.py", line 22, in highscore2
  8.     print columnize(col_value, column_width),
  9.   File "D:\Python24\Test.py", line 5, in columnize
  10.     nSpaces = width - len(word)
  11. TypeError: len() of unsized object
  12.  
  13.  
len(int) returns an error.
This works:
Expand|Select|Wrap|Line Numbers
  1. def columnize(word, width):
  2.     nSpaces = width - len(word)
  3.     if nSpaces < 0:
  4.         nSpaces = 0
  5.     return word + (" " * nSpaces)
  6.  
  7. def highscore2():
  8.     column_width = 18
  9.     """
  10.     scores = open("scores", "r")
  11.     oldscores = pickle.load(scores)
  12.     scores.close()
  13.     """    
  14.  
  15.     oldscores = [(300, 'John', 1, 300, 12), (200, 'Jane', 200, 3, 4), (106, 'Bajs', 1, 106, 9), (102, 'Hej', 1, 102, 9), (83, 'test', 2, 41, 48), \
  16.                   (68.700513199546208, 'Testny', 1, 68, 14.555932021867418), (66, 'Runk', 1, 66, 15), (58, 'test', 1, 58, 16), \
  17.                   (53, 'Test4', 1, 53, 18)]
  18.  
  19.  
  20.     header = ('Total Score', 'Name', 'Times Played', 'Median Value', 'Total time played (sec)')
  21.  
  22.     for title in header:
  23.         print columnize(title, column_width),
  24.     print
  25.  
  26.     for item in oldscores:
  27.         for col_value in item:
  28.             print columnize(str(col_value), column_width),
  29.         print            
  30.  
  31. if __name__ == '__main__':
  32.     try:
  33.         highscore2()
  34.     finally:
  35.         del highscore2
  36.         del columnize
Expand|Select|Wrap|Line Numbers
  1. Total Score        Name               Times Played       Median Value       Total time played (sec)
  2. 300                John               1                  300                12                
  3. 200                Jane               200                3                  4                 
  4. 106                Bajs               1                  106                9                 
  5. 102                Hej                1                  102                9                 
  6. 83                 test               2                  41                 48                
  7. 68.7005131995      Testny             1                  68                 14.5559320219     
  8. 66                 Runk               1                  66                 15                
  9. 58                 test               1                  58                 16                
  10. 53                 Test4              1                  53                 18                
Nov 28 '06 #20

bartonc
Expert 5K+
P: 6,596
This is the Errormessage:

Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Total Score        Name               Times Played       Median Value       Total time played (sec)
  3.  
  4. Traceback (most recent call last):
  5.   File "D:\Python24\Test.py", line 25, in -toplevel-
  6.     highscore2()
  7.   File "D:\Python24\Test.py", line 22, in highscore2
  8.     print columnize(col_value, column_width),
  9.   File "D:\Python24\Test.py", line 5, in columnize
  10.     nSpaces = width - len(word)
  11. TypeError: len() of unsized object
  12.  
  13.  
My bad. Thanks BV.
Nov 28 '06 #21

P: 24
len(int) returns an error.
This works:
Expand|Select|Wrap|Line Numbers
  1. def columnize(word, width):
  2.     nSpaces = width - len(word)
  3.     if nSpaces < 0:
  4.         nSpaces = 0
  5.     return word + (" " * nSpaces)
  6.  
  7. def highscore2():
  8.     column_width = 18
  9.     """
  10.     scores = open("scores", "r")
  11.     oldscores = pickle.load(scores)
  12.     scores.close()
  13.     """    
  14.  
  15.     oldscores = [(300, 'John', 1, 300, 12), (200, 'Jane', 200, 3, 4), (106, 'Bajs', 1, 106, 9), (102, 'Hej', 1, 102, 9), (83, 'test', 2, 41, 48), \
  16.                   (68.700513199546208, 'Testny', 1, 68, 14.555932021867418), (66, 'Runk', 1, 66, 15), (58, 'test', 1, 58, 16), \
  17.                   (53, 'Test4', 1, 53, 18)]
  18.  
  19.  
  20.     header = ('Total Score', 'Name', 'Times Played', 'Median Value', 'Total time played (sec)')
  21.  
  22.     for title in header:
  23.         print columnize(title, column_width),
  24.     print
  25.  
  26.     for item in oldscores:
  27.         for col_value in item:
  28.             print columnize(str(col_value), column_width),
  29.         print            
  30.  
  31. if __name__ == '__main__':
  32.     try:
  33.         highscore2()
  34.     finally:
  35.         del highscore2
  36.         del columnize
Expand|Select|Wrap|Line Numbers
  1. Total Score        Name               Times Played       Median Value       Total time played (sec)
  2. 300                John               1                  300                12                
  3. 200                Jane               200                3                  4                 
  4. 106                Bajs               1                  106                9                 
  5. 102                Hej                1                  102                9                 
  6. 83                 test               2                  41                 48                
  7. 68.7005131995      Testny             1                  68                 14.5559320219     
  8. 66                 Runk               1                  66                 15                
  9. 58                 test               1                  58                 16                
  10. 53                 Test4              1                  53                 18                

But can i add new players to the highscore now.
Beacause now the highscore is part of the code:
Expand|Select|Wrap|Line Numbers
  1.     oldscores = [(300, 'John', 1, 300, 12), (200, 'Jane', 200, 3, 4), (106, 'Bajs', 1, 106, 9), (102, 'Hej', 1, 102, 9), (83, 'test', 2, 41, 48), \
  2.                   (68.700513199546208, 'Testny', 1, 68, 14.555932021867418), (66, 'Runk', 1, 66, 15), (58, 'test', 1, 58, 16), \
  3.                   (53, 'Test4', 1, 53, 18)]
  4.  
Nov 28 '06 #22

P: 24
Okey... i get it now... thank you very much for your help! I truly mean it!
Nov 28 '06 #23

bartonc
Expert 5K+
P: 6,596
Okey... i get it now... thank you very much for your help! I truly mean it!
You're welcome, Max.
Nov 28 '06 #24

P: 24
i Have one last question:

What does this part do?
Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.     try:
  3.         highscore2()
  4.     finally:
  5.         del highscore2
  6.         del columnize
  7.  
what is "del"?
Nov 28 '06 #25

bartonc
Expert 5K+
P: 6,596
i Have one last question:

What does this part do?
Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.     try:
  3.         highscore2()
  4.     finally:
  5.         del highscore2
  6.         del columnize
  7.  
what is "del"?
It means delete from memory. I never worry about this. Python takes care of cleaning up memory.
Nov 28 '06 #26

bvdet
Expert Mod 2.5K+
P: 2,851
It means delete from memory. I never worry about this. Python takes care of cleaning up memory.
It's a habit I have developed which is not necessary. This works fine:
Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.        highscore2()
Nov 28 '06 #27

P: 24
It's a habit I have developed which is not necessary. This works fine:
Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.        highscore2()
But what does this mean then?
Nov 28 '06 #28

bvdet
Expert Mod 2.5K+
P: 2,851
But what does this mean then?
The code I posted could be considered a module. To test the module, you need some means of calling the function 'highscore2'.
Quote Python Essential Reference - "Each module defines a variable '__name__' that contains the module name. Programs specified on the command line or entered interactively run inside the '__main__' module."
In our case, the function 'highscore' is only executed if run as a script, but not if imported as a module.
Nov 28 '06 #29

bartonc
Expert 5K+
P: 6,596
But what does this mean then?
It's a habit I have developed which is not necessary. This works fine:
Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.        highscore2()
I call this "standard module test code".
Nov 28 '06 #30

P: 24
ok.... now i understand!
Nov 28 '06 #31

Post your reply

Sign in to post your reply or Sign up for a free account.