Python and Highscore.
Question posted by: cromoglic
(Newbie)
on
March 28th, 2008 01:40 AM
Hello! I have been making a "guess what number the computer thinks of"-game in python (text-only) for educational reasons. Now, i want to implement a highscore in the code, which writes the best three players with names and number of attempts. First, I'll just show you my game, but nevermind the code in that one:
-
#Importere modulen random:
-
import random
-
#thenumber tilsvarer nå random.randint(0, 100) som er et tilfeldig tall mellom 0 og 100)
-
thenumber = random.randint(0, 100)
-
# Et tappert forsøk på en loop.
-
loop = 1
-
-
#Definerer choice.
-
choice = 0
-
forsøk = 0
-
-
#Så til selve gjettedelen av scriptet :)
-
-
print "It is a number between 0 and 100. Can you guess it?"
-
print "Guess-the-number-game made by CromogliC"
-
print "Just type in a number of your own choice and press enter!"
-
-
yourname = raw_input("Please type in your name here: ")
-
-
while loop == 1:
-
choice = input("What number do you think is is?: ")
-
if choice == thenumber:
-
forsøk = forsøk +1
-
print "Amazing," + " " + yourname + "!"
-
print "You have guessed the right number!"
-
print "You are victorious!"
-
print "Tries used:"
-
print forsøk
-
wins = forsøk
-
loop = 0
-
print "Restart? y for yes. n for no."
-
restart = raw_input("Do you want to restart?: ")
-
if restart == "y":
-
forsøk = 0
-
#User restart!
-
loop = 1
-
elif restart == "n":
-
loop = 0
-
print "Game Over!"
-
exit()
-
elif choice < thenumber:
-
print "Nope, you have got to go higher!"
-
forsøk = forsøk +1
-
loop = 1
-
elif choice > thenumber:
-
print "Nope, you have got to go lower!"
-
forsøk = forsøk +1
-
loop = 1
-
elif choice > 100:
-
print "I am sorry, but you cannot pick a number above 100!"
-
loop = 1
Explanation: The notes are just explaining what the different sections does. nevermind those at all - they are in norwegian because i am a norwegian^^
Forsøk (in english attempts/tries) indicates how many attempts the user have used on guessing the right number. I did not plan on getting a highscore for this game, but now I've changed my mind. However, the integration of the actual highscore-code might be a little harder then. (Am I right?:P)
Now, to the actual highscore-code. I found a highscore from a previous post in here, but I am rather new to Python, and therefore had some trouble using it. Well, here is it (a little bit modifyed, as i tried to make it work on my own):
-
def hasHighScore(score):
-
#opens guessnumberhighscore.txt
-
infile = open("guessnumberhighscore.txt",'r')
-
scores = [0,0,0]
-
names = ["","",""]
-
-
#reads in scores from guessnumberhighscore.txt
-
i=0
-
for line in infile.readlines():
-
scores[i],names[i] = string.split(line,"\t")
-
names[i]=string.rstrip(names[i])
-
i += 1
-
infile.close()
-
-
#compares player's score with those in guessnumberhighscore.txt
-
i=0
-
for i in range(0,len(scores)):
-
if(score in(scores[i])):
-
return True
-
else:
-
return False
-
-
def setHighScores(score,name):
-
#opens guessnumberhighscore.txt
-
infile = open("guessnumberhighscore.txt",'r')
-
scores = [0,0,0]
-
names = ["","",""]
-
-
scores = [0,0,0]
-
#reads in scores from guessnumberhighscore.txt
-
i=0
-
for line in infile.readlines():
-
scores[i],names[i] = string.split(line,"\t")
-
scores[i]=int(scores[i])
-
names[i]=string.rstrip(names[i])
-
i += 1
-
infile.close()
-
-
#shuffles thru the guessnumberhighscore.txt and inserts player's score if
-
#higher than those in file
-
i=len(scores)
-
while(score == scores[i-1] and i>0):
-
i -= 1
-
scores.insert(i,score)
-
names.insert(i,name)
-
scores.pop(len(scores)-1)
-
names.pop(len(names)-1)
-
-
#writes new guessnumberhighscore.txt
-
outfile = open("guessnumberhighscore.txt","w")
-
-
outfile.write (" High Score Name \n")
-
outfile.write ("-------------------------------------------------\n")
-
-
i=0
-
for i in range(0,len(scores)):
-
outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
-
outfile.close()
-
-
-
#adds player's score to high score list if high enough
-
if(hasHighScore(wins) == True):
-
setHighScores(wins,yourname(wins))
-
Can anyone help me out a little?;)
|
|
March 28th, 2008 12:50 PM
# 2
|
Re: Python and Highscore.
-
def readHighScores():
-
#opens guesshighscores.txt
-
infile = open("guesshighscores.txt",'r')
-
scores = [0,0,0]
-
names = ["","",""]
-
-
#reads in scores from guesshighscores.txt
-
for idx, line in enumerate(infile):
-
scores[idx],names[idx] = tuple(line.strip().split())
-
infile.close()
-
-
return scores, names
-
-
-
def hasHighScore(score):
-
#opens guesshighscores.txt
-
scores, names = readHighScores()
-
-
#compares player's score with those in guesshighscores.txt
-
for elem in scores:
-
if int(score) < int(elem):
-
return True
-
return False
-
-
def setHighScores(score, name):
-
#opens guesshighscores.txt
-
scores, names = readHighScores()
-
-
# re-writes the list of highscores
-
for idx, elem in enumerate(scores):
-
if score > elem:
-
continue
-
scores.insert(idx, score)
-
names.insert(idx, name)
-
scores.pop()
-
names.pop()
-
break
-
-
#writes new guesshighscores.txt
-
outfile = open("guesshighscores.txt","w")
-
-
i=0
-
for i in range(0,len(scores)):
-
outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
-
outfile.close()
-
outfile = open('guesshighscores.txt', 'r')
-
print outfile.read()
-
outfile.close()
What was it that gave you trouble? I've posted some general fixes above (just a few things I noticed off the bat). But please let us know how you were having trouble.. was it syntax errors? Just wasn't doing what was expected? Elaborate...
|
|
March 28th, 2008 01:36 PM
# 3
|
Re: Python and Highscore.
Thank you:) Well, first of all i need a variable that writes to file after each successfully ended game. How do I do this? Can I just modify the game script, renaming all my score and name variables so they match with the variables for score and names in the HighScore code?
About the code: Yeah, last time i got some syntax errors (blocks and stuff, which I fixed easily, and one syntax error for "while score scores[i-1] and...", cant remember the exact error, but it was a syntax error caused by the word "scores". Might have been "scores is not defined", although one of the first lines defines scres by: scores = [0,0,0]. Anyways, your fixes seems to have fixed the problem.
|
|
March 28th, 2008 01:44 PM
# 4
|
Re: Python and Highscore.
Quote:
Can I just modify the game script, renaming all my score and name variables so they match with the variables for score and names in the HighScore code?
|
Not necessary, since the high score code is all functions. As long as you're passing the correct values, you will achieve the desired result
|
|
March 28th, 2008 01:56 PM
# 5
|
Re: Python and Highscore.
Hmm. My problem, at the moment, is making the highscore-code to read from my game-code. I'll post all of it here:
-
-
#Importere modulen random:
-
import random
-
#thenumber tilsvarer nå random.randint(0, 100) som er et tilfeldig tall mellom 0 og 100)
-
thenumber = random.randint(0, 100)
-
# Et tappert forsøk på en loop.
-
loop = 1
-
-
#Definerer choice.
-
choice = 0
-
forsøk = 0
-
-
#Så til selve gjettedelen av scriptet :)
-
-
print "It is a number between 0 and 100. Can you guess it?"
-
print "Guess-the-number-game made by CromogliC"
-
print "Just type in a number of your own choice and press enter!"
-
-
yourname = raw_input("Please type in your name here: ")
-
-
while loop == 1:
-
choice = input("What number do you think is is?: ")
-
if choice == thenumber:
-
forsøk = forsøk +1
-
print "Amazing," + " " + yourname + "!"
-
print "You have guessed the right number!"
-
print "You are victorious!"
-
print "Tries used:"
-
print forsøk
-
wins = forsøk
-
loop = 0
-
print "Restart? y for yes. n for no."
-
restart = raw_input("Do you want to restart?: ")
-
if restart == "y":
-
thenumber = random.randint(0, 100)
-
forsøk = 0
-
#User restart!
-
loop = 1
-
elif restart == "n":
-
loop = 0
-
print "Game Over!"
-
exit()
-
elif choice < thenumber:
-
print "Nope, you have got to go higher!"
-
forsøk = forsøk +1
-
loop = 1
-
elif choice > thenumber:
-
print "Nope, you have got to go lower!"
-
forsøk = forsøk +1
-
loop = 1
-
elif choice > 100:
-
print "I am sorry, but you cannot pick a number above 100!"
-
loop = 1
-
-
def readHighScores():
-
#opens guesshighscores.txt
-
infile = open("guesshighscores.txt",'r')
-
scores = [0,0,0]
-
names = ["","",""]
-
-
#reads in scores from guesshighscores.txt
-
for idx, line in enumerate(infile):
-
scores[idx],names[idx] = tuple(line.strip().split())
-
infile.close()
-
-
return scores, names
-
-
-
def hasHighScore(score):
-
#opens guesshighscores.txt
-
scores, names = readHighScores()
-
-
#compares player's score with those in guesshighscores.txt
-
for elem in scores:
-
if int(score) < int(elem):
-
return True
-
return False
-
-
def setHighScores(score, name):
-
#opens guesshighscores.txt
-
scores, names = readHighScores()
-
-
# re-writes the list of highscores
-
for idx, elem in enumerate(scores):
-
if score > elem:
-
continue
-
scores.insert(idx, score)
-
names.insert(idx, name)
-
scores.pop()
-
names.pop()
-
break
-
-
#writes new guesshighscores.txt
-
outfile = open("guesshighscores.txt","w")
-
-
i=0
-
for i in range(0,len(scores)):
-
outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
-
outfile.close()
-
outfile = open('guesshighscores.txt', 'r')
-
print outfile.read()
-
outfile.close()
-
|
|
March 28th, 2008 02:07 PM
# 6
|
Re: Python and Highscore.
Well what do you mean read from your code? You never call any of the highschore functions, so obviously nothing is going to happen. Basically all you need to do is check if the player's score is the high score when they win. If it returns true then call the set high score function with their name and score.
|
|
March 28th, 2008 02:46 PM
# 7
|
Re: Python and Highscore.
so if i add something similiar to
while forsøk < 0:
and then the highscore-code it should work? Then, it will check the txt-file as long as my result is greater than 0
|
|
March 28th, 2008 03:16 PM
# 8
|
Re: Python and Highscore.
No. Do you know what calling a function is?
You would want something more like this (which is when you have determined the player has won...):
-
forsøk = forsøk +1
-
print "Amazing," + " " + yourname + "!"
-
print "You have guessed the right number!"
-
print "You are victorious!"
-
print "Tries used:", forsøk
-
wins = forsøk
-
if hasHighScore(wins):
-
setHighScores(wins, yourname)
|
|
March 28th, 2008 05:07 PM
# 9
|
Re: Python and Highscore.
Hmm, I thought "commands" such as "if" and "while" etc. were calling commands. Bare in mind that I started with python a week ago:P I will try your suggestion, thank you:)
|
|
March 28th, 2008 06:19 PM
# 10
|
Re: Python and Highscore.
Well, i tried to add the code you gave me, with the result of setHighScores etc. not being defined - easy enough, I just put the highscorepart over the actual game-part. Now, i get this error when I've guessed the right number:
Traceback (most recent call last):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 82, in ?
if hasHighScore(wins):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 29, in hasHighScore
scores, names = readHighScores()
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 15, in readHighScores
infile = open("guesshighscores.txt",'r')
IOError: [Errno 2] No such file or directory: 'guesshighscores.txt'
The highscorecode is supposed to write a new guesshighscores.txt, but as it didnt, I made a textfile with that name manually. The error persists. I found out that I had called the file i made guesshighscores.txt, which results in the full name: guesshighscores.txt.txt (as the file extension is added). When I fixed this, the "game" runs without errors, but it doesnt write anything to my file. It seems like the call-function or the highscore-codepart does not work properly/isnt configured properly, but I cant see whats wrong. Help me?:D
|
|
March 28th, 2008 06:26 PM
# 11
|
Re: Python and Highscore.
It would seem to me that if the file is empty, then the hasHighScore function will never have anything to compare the score to; thereby never being able to return True.
In your txt file make entries with a score of 100 and a random name like CPU1, 2 and 3 or similar.
Similarly, if you're looking to learn good programming practices, at the initialization of your program you could do the following:
-
import os
-
-
if not os.path.exists('guesshighscores.txt'):
-
fh = open('guesshighscores.txt', 'w')
-
fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')
-
fh.close()
That way you can be sure that you won't get a file does not exist error, as well as there being default scores... HTH
|
|
March 28th, 2008 06:29 PM
# 12
|
Re: Python and Highscore.
Thank you, you have been really helpful :)
Could you explain the bit about CPU/n? I did not understand that part:P (just for learning)
|
|
March 28th, 2008 06:33 PM
# 13
|
Re: Python and Highscore.
Oh, by the way, the code prevents errors from appearing, but the program still wont write to file.
|
|
March 28th, 2008 06:50 PM
# 14
|
Re: Python and Highscore.
\n is what's known as an escape character... any character that has a \ in front of it is an escape character (\n is the escape character for "new line".. so it's like pressing enter in a text editor... it creates a "new line").
-
fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')
is simply shorter than writing
-
fh.write('100 CPU1\n')
-
fh.write('100 CPU2\n')
-
fh.write('100 CPU3\n')
So when you say it's not writing to file .. are you sure you're checking the correct file? Does it print out the correct high scores ? I'm thinking that the file is in a different location than where you imagine it to be. A quick " print os.getcwd() " at the beginning of your program will tell you the current working directory, which is where the highscore file is being read/written
|
|
March 28th, 2008 07:33 PM
# 15
|
Re: Python and Highscore.
Yes, I've learnt that the working directory usually is where the actual script is saved. To be sure, i tried your command, which proved that i was right about the directory. However, when i tried to delete the txt-file i manually created earlier, it worked. Now, it looks damn messy, so I'll start working on the "layout" now;) Thank you alot for your help:)!
By the way, will I be able to make line at the top containing for instance PlayersName Score
which will stand the "for ever" by adding a /n at the beginning of the fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')-line?
now, I am starting to get this error:
Traceback (most recent call last):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 92, in ?
if hasHighScore(wins):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 39, in hasHighScore
scores, names = readHighScores()
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 31, in readHighScores
scores[idx],names[idx] = tuple(line.strip().split())
ValueError: too many values to unpack
Even though i didnt touch anything:P For me, it seems like this occurs every time my score is above 9, but I could be wrong:P
|
|
March 28th, 2008 07:43 PM
# 16
|
Re: Python and Highscore.
Quote:
By the way, will I be able to make line at the top containing for instance PlayersName Score
which will stand the "for ever" by adding a /n at the beginning of the fh.write('100 CPU1\n100 CPU2\n100 CPU3\n')-line?
|
I don't know what you mean by "for ever" and adding /n .... The escape characters are \ not / ... But if you add a line to the beginning of the file you must account for that and skip over it when reading from the file... which leads me into the second part of your post:
Quote:
Traceback (most recent call last):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 92, in ?
if hasHighScore(wins):
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 39, in hasHighScore
scores, names = readHighScores()
File "C:\Documents and Settings\Omni Potent\Desktop\Python scripting\Guessnumbergame\guessnumber.py", line 31, in readHighScores
scores[idx],names[idx] = tuple(line.strip().split())
ValueError: too many values to unpack
|
Basically this means that there is more than just two items in the line. One way to debug this is to split that line up in the following way:
- scores[idx],names[idx] = tuple(line.strip().split())
-
# Split the above line into the following lines for debug purposes
-
line = line.strip().split()
-
print line # This will show you what the script is reading from the file line by line
-
if len(line) == 2:
-
scores[idx] = line[0]
-
names[idx] = line[1]
-
else:
-
print 'This line is not formatted correctly: %s' % line
Before the suspect line of code was assuming that only two things were on each line... score and name, however if for some reason that goes sour you'll see the above error. Basically it is cause by assigning two variables to something when there is more than two thing to be assigned... example from IDLE:
-
>>> tupp = ('1a', '1b')
-
>>> a, b = tupp
-
>>> a
-
'1a'
-
>>> b
-
'1b'
-
>>> tupp = ('2a', '2b', '2c')
-
>>> a, b = tupp
-
Traceback (most recent call last):
-
File "<input>", line 1, in ?
-
ValueError: too many values to unpack
-
>>> a, b, c = tupp
-
>>> tupp
-
('2a', '2b', '2c')
-
>>>
Get it? So try to debug your code by seeing which line is causing this error and then try to solve the problem with your wits! ;)
|
|
March 28th, 2008 07:53 PM
# 17
|
Re: Python and Highscore.
well, here is what I did:
-
-
#reads in scores from guesshighscores.txt
-
for idx, line in enumerate(infile):
-
line = line.strip().split()
-
print line # This will show you what the script is reading from the file line by line
-
if len(line) == 2:
-
scores[idx] = line[0]
-
names[idx] = line[1]
-
else:
-
print 'This line is not formatted correctly: %s' % line
-
infile.close()
Len len(line) is obviously not equal to 2, because i get the This line is not formatted correctly blablabla-message.
the result of the highscore is like this:
0
5 Lars
100 CPU1
(first of all, it is not possible to get 0, and also, a name should appear^^)
the "error" i get now is:
['8', 'The', 'Lars']
This line is not formatted correctly: ['8', 'The', 'Lars']
['100', 'CPU1']
['100', 'CPU2']
['8', 'The', 'Lars']
This line is not formatted correctly: ['8', 'The', 'Lars']
['100', 'CPU1']
['100', 'CPU2']
0
5 Lars
100 CPU1
for me, it seems like the highscore cant handle me putting in a double name in the raw_input called yourname.
|
|
March 28th, 2008 08:16 PM
# 18
|
Re: Python and Highscore.
Quote:
it seems like the highscore cant handle me putting in a double name in the raw_input called yourname.
|
That's correct. When reading from file your code only performs a split() and then assumes that item[0] is score and item[1] is name. Since split() simply splits at white space you'll want to modify it so that it only splits at tabs (ie, split('\t'), see there's another escape character \t which is for tab). Then when writing to file make sure you put \t between your score and your names. This should allow you to take a "multiple word" name and read/write in the same manner.
|
|
March 28th, 2008 08:25 PM
# 19
|
Re: Python and Highscore.
fh.write('100 CPU1\t\n100 CPU2\t\n100 CPU3\t\n')
works, now I can use double names properly, but the other errors are still there:
['0']
This line is not formatted correctly: ['0']
['5', 'Lars']
['100', 'CPU1']
['0']
This line is not formatted correctly: ['0']
['5', 'Lars']
['100', 'CPU1']
0
6 The Lars
5 Lars
I do not get this. Can you help me out?^^
|
|
March 31st, 2008 12:17 PM
# 20
|
Re: Python and Highscore.
Post the contents of your high score text file and maybe it'll be a little clearer
|
|
March 31st, 2008 01:32 PM
# 21
|
Re: Python and Highscore.
Well, the contents of the textfile looks like this:
0
6 The Lars
5 Lars
|
|
March 31st, 2008 02:22 PM
# 22
|
Re: Python and Highscore.
Your problem is that you have a line with only a 0... The code is telling you that it's not formatted correctly, so that should've given you a hint.
Not the answer you were looking for? Post your question . . .
189,285 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).
|
|
|
Latest Articles: Read & Comment
Top Python Forum Contributors
|