Hi guys

I've made a hangman game and now i want to make a highscore list for it. I was thinking that i would probably have to export the data to like excel or something, but I have no idea how to do this. Also if there is a better way to make one can you please tell me. Thanks.

Recommended Answers

All 6 Replies

Study about list, sort and open.

I was told by someone else to use a csv, can anyone give me an example oh to put information into one and then another example of how to bring it up again for further use?

You could see for example http://www.daniweb.com/code/snippet293490.html for ideas. For simple unquoted data csv module is not needed, it could be usefull if need quoting of data and interchange of information with other programs with strange ideas of what csv means.

Here is a simple context to store the high scores in a csv file

from contextlib import contextmanager
import csv

@contextmanager
def scorelist(filename):
    """Maintain a csv file with a list of scores"""
    try:
        with open(filename, "rb") as fin:
            reader = csv.reader(fin, delimiter=",")
            L = [ (row[0], int(row[1])) for row in reader ]
    except IOError:
        L = []
    try:
        yield L
    finally:
        with open(filename, "wb") as fout:
            writer = csv.writer(fout, delimiter=",")
            writer.writerows(L)
    
    
def main():
    # using a with statement ensures that the scores are stored at the end of the game
    # or if an error occurs.
    with scorelist("scores.csv") as scores:
        scores.append(("kermit", 10))
        scores.append(("piggy", 15))
        print(scores)

main()

You may add code to sort the scores, or shorten the list, etc.

okay i did this

import csv
import string
import random
from HMGraphics import HangingMan

bKeepPlaying = True
while bKeepPlaying == True:
## ~-~-~-~-~-~-~-~-~-~-~ Various Declarations ~-~-~-~-
    sWords= open("Dictionary.txt", "r")
    sRawText = sWords.read()

    sWords=[]
    iStart=0
    iEnd=0
    iIndex =-1
    iWordNumber = 0
    iErrors = 0
    iScore = 0


    iGuesses = 0
    sLettersUsed = ""

    ScoreWriter = csv.writer(open('highscore.csv','wb'), delimiter = ' ',
                             quotechar = '|', quoting = csv.QUOTE_MINIMAL)
    ScoreReader = csv.reader(open('highscore.csv','rb') , delimiter = ' ', quotechar='|')


    def DrawErrors():

        if iErrors == 0:
            print HangingMan[0]
        elif iErrors == 1:
            print HangingMan[1]
        elif iErrors == 2:
            print HangingMan[2]
        elif iErrors == 3:
            print HangingMan[3]
        elif iErrors == 4:
            print HangingMan[4]
        elif iErrors == 5:
            print HangingMan[5]
        elif iErrors == 6:
            print HangingMan[6]
        elif iErrors == 7:
            print HangingMan[7]
        elif iErrors == 8:
            print HangingMan[8]

    def ScoreWrite(name,score):
        ScoreWriter.writerow([name, score])


    ## ~-~-~-~-~-~-~-~-~-~-~ Peel off words from list -~-~-
    for char in sRawText:
        iIndex += 1
        if(char == "~" and iIndex < 1):
            iEnd = iIndex
        if(char == "~" and iIndex > 1):
            iStart = iEnd
            iEnd = iIndex
            iWordNumber += 1
            sWords.insert(iWordNumber,sRawText[iStart+1:iEnd])


    ## ~-~-~-~-~-~-~-~-~-~-~ Create copy of random word -~-~-
    ## ~-~-~-~-~-~-~-~-~-~-~ and write it as a series of underscores-



    iRandomWord = int(random.random()*850)
    sAnswer = sWords[iRandomWord]
    sAnswer = list(sAnswer)
    sReveal = ""
    sReveal += len(sAnswer) * "-"
    sReveal = list(sReveal)


    ## ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~Main Game Loop-~-~-~-~-~-
    print "".join(sAnswer)
    print "".join(sReveal)




    while True:
        sLetterGuess = str(raw_input("Please choose a letter "))
        
        if sAnswer.count(sLetterGuess) == 0:
            iErrors += 1
            sLettersUsed += sLetterGuess
            DrawErrors()
            print sLettersUsed
        else:
            for i in range(len(sReveal)):
               if sAnswer[i]== sLetterGuess:
                   sReveal[i] = sLetterGuess
            print "".join(sReveal)
            sLettersUsed += sLetterGuess
            print "letters used : " + sLettersUsed
            
        if sReveal.count("-") == 0:
            print "You Won"
            iScore += (10 - iErrors)
            sPlayAgain = raw_input("would you like to play again (y/n)? ")
            if sPlayAgain == 'y':
                break
            else:
                bKeepPlaying = False
                sPlayerName = raw_input("Please enter your name for the highscore list: ")
                ScoreWriter.writerows([sPlayerName, str(iScore)])
                break
        elif iErrors >= 8:
            print "You Lost"
            sPlayAgain = raw_input("would you like to play again (y/n)? ")
            if sPlayAgain == 'y':
                break
            else:
                bKeepPlaying = False
                sPlayerName = raw_input("Please enter your name for the highscore list: ")
                ScoreWriter.writerows([sPlayerName, str(iScore)])
                break


print "Your score was " + str(iScore)
print "These are the highscores"
for row in ScoreReader:
    print ', '.join(row)
print "Thanks for playing!"

## ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-

but for some reason there's a problem with printing the information from the csv file? Anyone have a clue on what this may be

You have two different file pointers to the same file, one for reading and one for writing (and you open it again on every pass through the while() loop). The results are unpredictable for a situation like that. Read the file into memory and then close the file. You can then open it for writing/appending. Also, code like this should be cleaned up and functions should be outside of the while() loop in which case the function would not know what iErrors is (Python naming conventions). Some info on Function parameters.

def DrawErrors():
 
        if iErrors == 0:
            print HangingMan[0]
        elif iErrors == 1:
            print HangingMan[1]
        elif iErrors == 2:
            print HangingMan[2]
        elif iErrors == 3:
            print HangingMan[3]
        elif iErrors == 4:
            print HangingMan[4]
        elif iErrors == 5:
            print HangingMan[5]
        elif iErrors == 6:
            print HangingMan[6]
        elif iErrors == 7:
            print HangingMan[7]
        elif iErrors == 8:
            print HangingMan[8]
##
##-----------  replace with -------------------------------------
def draw_errors(i_errors, hanging_man):
    if 0 <= i_errors <= 8:
        print hanging_man[i_errors]
    else:
        print "Non-legal value for i_errors =", i_errors
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.