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?;)
21 5386 -
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...
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.
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
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()
-
-
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.
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
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)
-
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:)
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
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
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)
Oh, by the way, the code prevents errors from appearing, but the program still wont write to file.
\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
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
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:
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! ;)
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.
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.
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?^^
Post the contents of your high score text file and maybe it'll be a little clearer
Well, the contents of the textfile looks like this:
0
6 The Lars
5 Lars
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.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Sarah |
last post by:
Hello!
Does anybody know a script for a puzzle with Highscore?
Many thanks before, Sarah
|
by: Emile van Sebille |
last post by:
QOTW: "If we get 2.3.3c1 out in early December, we could release 2.3.3 final
before the end of the year, and start 2004 with a 100% bug-free codebase
<wink>." -- Tim Peters
"cjOr proWe vbCould...
|
by: MaxLindquist |
last post by:
Hi! I want to make a highscore for a game i am making. How might i do that?
Thanks
|
by: zuuperman |
last post by:
Hi folks
I have a little problem converting from an access database to the SQL
server
I need to have a highscore that shows the top 10 scores, grouped by
email.
In my access db i had this...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |