Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.
Related
What I want to do is have Python generate a number between 1 and 6, then add 6 to that number which I have got it to do and provide me with a result, however what I can't seem to figure out is how to make that value able to be called so it can go up and down during the game, here is what I have so far:
import random
import time
Name = input("Before we get started lets get your character created, tell me what is your name?")
print()
print ("Welcome ",Name," to the adventure of a lifetime. The next thing you will need to do is sort out your character stats. This will require dice rolls which we will do within the game.")
print()
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill=random.randint(1,6)
time.sleep(2)
print("I rolled a", skill, " I will now add 6 to this so your skill is", skill+6)
skill=skill+6
print()
return skillroll
skillroll()
I just cant see how to get that final answer out so I can use it during the game-play.
A friend of mine sent me this to help
https://github.com/protocol7/python-koans/blob/master/python%202/koans/about_classes.py
But I just cant see how this relates and every answer I found on Stackoverflow is for different languages.
Simply use:
import random
random.randrange(1, 7)
to get any number between 1 and 6.
Your code becomes:
import random
import time
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill = random.randrange(1, 7)
time.sleep(2)
print("I rolled a ", skill, ". I will now add 6 to this so your skill is", skill+6, "\n")
skill=skill+6
return skillroll # What if N??
Name = input("Before we get started lets get your character created, tell me
what is your name?")
print ("\nWelcome ",Name," to the adventure of a lifetime. The next thing you
will need to do is sort out your character stats. This will require dice
rolls which we will do within the game.\n")
skillroll()
I am new to python, My first project that I am still working on is a kind of a game in which you throw a dice and stuff like that, so it's pretty much a dice simulator.
Before the user actually starts the game I have made the program ask them questions like; "Type 'start' on keyboard to begin the game, and this I am doing with raw_input.
Here's the problem:- I want to make only the input 'start' possible to write, if something else is written, the game doesn't start. I hope you understand me
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name);
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
You just need if_else
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
if start=='start':
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name)
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
else:
print("XYZ message")
Im a student, and just started learning python a month back, so right now, I have only learnt the basics. My teacher had given me a question like this, and the problem is, I dont know how to rerun a program, suppose, after finding the area of a particular shape, I want it to loop back to printing the first statement.
Is there any way of doing that without re-running the program using the "F5" key?
print "1. Triangle"
print "2. Circle"
print "3. Rectangle"
shape= input("Please Select the serial number =")
if shape==1:
a=input("Base =")
b=input("Height =")
area=0.5*a*b
print area
if shape==2:
a=input("Radius =")
area=3.14*a*a
print area
if shape==3:
a=input("Width")
b=input("Length")
area=a*b
print area
If you want to restart, just use a simple while loop.
while True:
# Your lovely code
Then just put some validation at the end:
again = raw_input("Play again? ")
if again.startswith('n') or again.startswith('N'):
break
else:
continue
So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.
In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively
First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.
I am having trouble with the randint usage of exercise 43 in Learn python the hard way link to exercise. Assuming I follow Zed Shaw's code perfectly in all other parts of the program, and I have from random import randint, when I run the program and type the 3 digit passcode into the keypad, it returns a "BZZZZEDDD!". Here is that section of code:
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
Lets say in the guess = raw_input("[keypad]> ") when running the program I type in "368".
Shouldn't that be within the parameters of code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) and be TRUE for if guess ==code:? Instead it runs it as if guess != code and returns a "BZZZZEDDD!"
Your guess of 368 is within the possible range for the code, but that's not what the while loop is checking. The line
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
will generate a string of three random digits. The code could be anything between 111 and 999 (except there can be no zeroes) and you have no way of knowing exactly what it is as the program currently stands. At the bottom of the lesson, under Study Drills, the author says:
Add cheat codes to the game so you can get past the more difficult
rooms. I can do this with two words on one line.
Presumably, this code is one of the rooms he's talking about. Try adding something that will give you a hint of the code.