lunes, 26 de mayo de 2014

Guess the number, part 3

I've been trying to create a high score system for the game, but it has proven to be quite challenging! At first I thought I'd use a dictionary for the players' name and score, but after a while I noticed that a) I wouldn't be able to sort it and b) printing key and value doesn't feel intuitive. So I went down a very interesting road, involving the following concepts:

Classes

After some though, I decided that a player class would be the way to go. It simply contains two attributes, name and score, and both are generated right when an object is instanced:

class player:
    def __init__(self,name_arg,score_arg):
        self.name = name_arg
        self.score = score_arg

Files

This was all new to me! I had never dumped binary data into a file before. The whole point is to store a list of player objects in a file in order to be able to access this information in different playing sessions. I did this through the 'pickle' module. It works something like this:



import pickle
newPlayer = player('Dick',1000)
newPlayer2 = player('Jane',500)
newPlayer3 = player('Harry',300)
playerList = [newPlayer,newPlayer2,newPlayer3]

scoresFile = open('scores','wb')
pickle.dump(playerList,scoresFile)
scoresFile.close()

At this point, a file called 'scores' gets created, and the data from the playerList is stored in it. You access it again like this:

scoresFile = open('scores','rb')
scoresList = pickle.load(scoresFile)

Sorting the list by score

This was the tricky part. In order for the list to behave like I wanted, I need to sort it, so I can display it correctly, and most importantly, in order to know if the player's score actually made the list or not.

Lists have a sort() method that do this job perfectly, but it needs that the list elements are sortable objects, so the question was: 'How do I make my class sortable?' This is the answer I found, although I still don't understand it fully:

class player:
    def __init__(self,pname,pscore):
        self.name = pname
        self.score = pscore
    def __lt__(self,other):
        self.score < other.score

I assume that __lt__ means 'lower than'. It appears to specify how to compare objects of this class. By whatever means, now the class 'player' is sortable, through its score attribute! To try it out, I made this function:

def CheckHighScores(score):

    scoresFile = open('scores','rb')
    scoresList = pickle.load(scoresFile)
    scoresList.sort()
    for i in scoresList:
        print(i.name + ' - ' + str(i.score))

It prints the list in perfect order!

I haven't finished implementing the high score system yet, but I wanted to share this information, because it was all pretty new and exciting for me. In the next post I'll hopefully have completed the program, and I'll show you the entire code!

1 comentario:

  1. Great work..looking forward for all your teachings...:) i wana be a good programmer.

    ResponderEliminar