Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
hi I have made a game in python were you need to input the specified number before the time runs out. I want to be able to save the top 5 high scores and display them at the end. i have surfed the web looking for solutions but being a amateur at python, I just cant tailor them to my coding. I want to save the name and the score preferably on one line using \t to separate them.
any answers would be much appreciated.
the game:
# number press game
import time
import random
print "Welcome to my Number Press Game"
print "the computer will display a number"
print "you will have to enter the number before the time runs out"
name = raw_input ("please enter your name: "+"\n")
print "\n"+"welcome to the game "+name
print "ready"
time.sleep (1)
print "steady"
time.sleep (1)
print "GO!"
#game
loop = -1
t = 3
while True:
loop = loop+1
x = random.randint(1,3)
print x
start = time.time()
num = input("the number is: ")
end = time.time()
elapsed = end - start
if elapsed > t and num == x:
print "CORRECT, but too slow"
break
elif num != x and elapsed < t:
print "\n"+"WRONG, but in time"
break
elif num != x and elapsed > t:
print "WRONG and too slow"
break
if num == x and elapsed< t:
print "CORRECT and in time"
if t>0.7:
t =t*0.9
print "you loose"
print name+" scored: "+str(loop)
Run this and see if it gives what you have in mind: This runs simulates playing the game n number of times. Then the highest scores is printed out as a list of all scores. Right here I have used y = 5, if you need 5 highest scores, I presume you need to play the game at least 5 times then the scores compared and the highest values printed as your highest scores: in the for loop. The highest_scores is then sorted to pick out the n highest scores you require. That said, you should review your logic it seems to be problematic. vote the answer if it helps. Cheers
import time
import random
high_score = []
def play_game():
print "Welcome to my Number Press Game"
print "the computer will display a number"
print "you will have to enter the number before the time runs out"
name = raw_input ("please enter your name: "+"\n")
print "\n"+"welcome to the game "+name
print "ready"
time.sleep (1)
print "steady"
time.sleep (1)
print "GO!"
loop = -1
t = 3
score = 0
while True:
loop = loop+1
x = random.randint(1,3)
print x
start = time.time()
num = input("the number is: ")
end = time.time()
elapsed = end - start
if elapsed > t and num == x:
print "CORRECT, but too slow"
break
elif num != x and elapsed < t:
print "\n"+"WRONG, but in time"
break
elif num != x and elapsed > t:
print "WRONG and too slow"
break
if num == x and elapsed< t:
print "CORRECT and in time"
score += 1
if t>0.7:
t = t*0.9
high_score.append(score)
print "you loose"
print name + " scored: "+ str(score)
print "All highest_scores =", high_score
highest_scores = sorted(high_score, reverse = True)
print "All highest_scores =",highest_scores[0:3]
y = 5
for i in range (y):
play_game()
Related
i would like to have a countdown for my rocket to life off but i just cant make it decrease the number it only stays the same can someone help me?
print("program is writen by someone")
name = input("program is runned by")
print(name,",if you are a pilot of the project please type pilot for the next question. If you are other please type your reason/role for u being here")
x = input("what is your reason for u being here")
if x == 'pilot':
print (name,"ok wlecome to the crew")
h = input ("is the hatch closed? please answer closed or no")
if h == 'closed':
import time as t
second = int(input ("very good please enter the needed for the countdown"))
for i in range(second):
print (str(second - 1)+ "second remaining \n")
t.sleep(1)
print ("time is up")
else:
print ("please check if the hatch is close")
else:
y = input("are you 600meters away from the spacecraft?")
if y == 'yes':
print ("have a nice time watching the show")
else:
print("please stand back untill u are 600 meter away from the aircraft")
You're not using the loop variable and printing the same second-1 value every time. You can use a decreasing range, e.g.:
for i in range(second, 0, -1):
print(f'{i} seconds remaining')
time.sleep(1)
or simply a while-loop:
while second:
print(f'{second} seconds remaining')
second -= 1
time.sleep(1)
(Notice that time.sleep() is called inside the loop body)
I was attempting to create a quiz and one of the criteria is to limit the time available to solve for each question in the quiz. I looked up certain tutorials but some require an input of x seconds for the timer to go off while others looked more like a stopwatch...
I was wondering how do I do like a background timer that ticks down as soon as the question is printed out and skips to the next question if, for example the 30-second period has ended? I'm clueless in the timer function and was having problems to even try to implement them onto my codes. Could someone give out a few pointers so I can sorta progress further in implementing a working timer?
Thank you!
EDITED section below:
The timer that I want to implement onto my coding:
import time
import threading
def atimer():
print("Time's up.")
a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")
This is the whole coding that I tried to implement the timer into.
I noticed that when I tried to define qtimer to just print 1 or 2 lines of statements the timer works but I want the timer to stop and go to second question or stop and give the user another attempt to retry the question, so I tried to attach a bunch of codes after the definition and it didn't work. I know I'm most probably doing something wrong here since I'm not quite familiar with time or threading functions. Is there a workaround?
def qtimer():
print("I'm sorry but your time is up for this question.")
print("You may have another attempt if you wish to, with reduced marks allocated.")
response1 = input("Type 'Yes' for another attempt, anything else to skip: ")
if response1 == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
class A:
def __init__(self, question, correctAnswer, otherAnswers, difficulty, explanation):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
self.diff = difficulty
self.expl = explanation
qaList = [A("What is COVID-19?", "Coronavirus Disease 2019", ["Wuhan virus", "I don't understand...", "Coronavirus Disease v19"], 1, "Explanation 1"),
A("What describes COVID-19?", "A disease", ["A virus", "A parasite", "A bacteriophage"], 1, "Explanation 2"),
A("What causes COVID-19?", "SARS-CoV-2", ["Coronavirus", "Mimivirus", "Rubeola Virus"], 1, "Explanation 3"),
A("Which of the following is used in COVID-19 treatment?", "Lopinavir / Ritonavir ", ["Midazolam / Triazolam", "Amiodarone", "Phenytoin"], 2, "Explanation 4"),
A("Which of the following receptors is used by COVID-19 to infect human cells?", "ACE-2 Receptors", ["ApoE4 Receptors", "TCR Receptors", "CD28 Receptors"], 3, "Explanation 5")]
corr = 0
marks = 0
random.shuffle(qaList)
for qaItem in qaList:
q_timer = threading.Timer(5.0, qtimer)
q_timer.start()
print(qaItem.question)
print("Possible answers are:")
possible = qaItem.otherAnsw + [qaItem.corrAnsw]
random.shuffle(possible)
count = 0
while count < len(possible):
print(str(count+1) + ": " + possible[count])
count += 1
print("Please enter the number of your answer:")
Answ = input()
Answ = str(Answ)
while not Answ.isdigit():
print("That was not a number. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
Answ = int(Answ)
while Answ > 4 or Answ < 1:
print("That number doesn't correspond to any answer. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
if possible[Answ-1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 1 * qaItem.diff
else:
print("Your answer was wrong.")
response = input("Would you want to try again? If so, input 'Yes' to attempt it again, if not just input whatever!")
if response == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
print("You answered " + str(corr) + " of " + str(len(qaList)) + " questions correctly.")
print("You have achieved a total score of " + str(marks) + ".")
Even with a timer, the main thread can't proceed past waiting for the user to input a number; so if the user doesn't nothing, the timer function runs, and once it has finished the main thread is still waiting for input at
print("Please enter the number of your answer:")
Answ = input()
You could have a global flag that the timer thread sets to tell the main thread to treat the input received as response1 in the timer code, and also have a flag to tell the timer that an answer was received, and so on, and it quickly becomes rather complicated.
So rather than trying to work around the blocking call to input by communicating between the timer and main thread, take the non-blocking input example from https://stackoverflow.com/a/22085679/1527 and stop the loop early if the time is up.
def timed_input(msg, timeout=10):
kb = KBHit()
print(msg)
end_time = time.time() + timeout
warn_time = 5
result = None
while True:
if kb.kbhit():
c = kb.getch()
if '0' <= c <= '9':
result = int(c)
break
print(c)
if time.time() > end_time:
print('time is up')
break
if time.time() > end_time - warn_time:
print(f'{warn_time}s left')
warn_time = warn_time - 1
kb.set_normal_term()
return result
# Test
if __name__ == "__main__":
result = timed_input('Enter a number between 1 and 4')
if result is None:
print('be quicker next time')
elif 1 <= result <= 4:
print('ok')
else:
print(f'{result} is not between 1 and 4')
Note also that breaking up into smaller functions helps make the code easier to follow, the logic of the test doesn't need to know about the logic of the timeout.
I have a homework task that was to create a quiz. It had to contain a list of a pre-defined function. I am very new to python and coding and can only just understand the basics. In my quiz, I have a counter that keeps track of questions wrong and right and displays them at the end of the quiz. Currently, the summary repeats itself counting down to the right answer. I'm very confused and the quiz is due tomorrow. If anyone has a simple score counter I can either replace mine with or can help fix mine it would be much appreciated :)
I have looked over the code but can't determine the cause as I'm very new
k = 1
while k==1:
#asks user a question
print("Q10 - When was the first ever official Formula 1 race?\n1:1850 2:1950 or 3:Yesterday")
q1 = input ("\n")
intcheck(q1)
#correct answer
if q1 == "2":
r.append(1)
print("Congrats you got it correct\n")
#wrong answer
else:
w.append(1)
print("Tough luck, you got that one wrong!")
# score counter
while len(r) > 0:
resultr += 1
r.remove(1)
while len(w) > 0:
resultw += 1
w.remove(1)
#final scoreboard
print ("===============================================")
print ("----------------End Game Summary---------------")
time.sleep(0.5)
print ("You got",resultw,"wrong and ",resultr," correct")
time.sleep(3)
print (" !Thanks for playing! ")
print ("===============================================")
As you're new to python, I will introduce you a little bit to the Object-oriented programming...
import time
class Question:
def __init__(self, question, answers, solution):
self.question = question
self.answers = answers
self.solution = solution
def ask_question(self):
print(self.question)
for ix, rep in enumerate(self.answers):
print(ix, ':', rep)
user_rep = int(input())
if user_rep == self.solution:
print("Congrats you got it correct")
return 1
else:
print("Tough luck, you got that one wrong!")
return 0
question_10 = "Q10 - When was the first ever official Formula 1 race?"
anwers_10 = ['1850', '1950', 'Yesterday']
solution_10 = 1
questions = [(question_10, anwers_10, solution_10)]
right, wrong = 0, 0
for q in questions:
quest = Question(q[0], q[1], q[2])
user_rep = quest.ask_question()
if user_rep == 1:
right += 1
else:
wrong += 1
#final scoreboard
print ("===============================================")
print ("----------------End Game Summary---------------")
time.sleep(0.5)
print ("You got",wrong,"wrong and ",right," correct")
time.sleep(3)
print (" !Thanks for playing! ")
print ("===============================================")
You just have to create each question like this :
question_10 = "Q10 - When was the first ever official Formula 1 race?"
anwers_10 = ['1850', '1950', 'Yesterday']
solution_10 = 1
And then to add each question to the questions list before the loop.
Fell free to ask any question !
The following code could a baseline:
import time
question_list = ["Q1 blabla", "Q2 blala", "Q3 blabla"]
size_question_list = len(question_list)
answer_list = ["answer 1", "answer 2", "answer 3"]
correct_answers = []
for k in range(size_question_list):
#asks user a question
print(question_list[k])
q = input ("your answer : ")
if q == answer_list[k]:
# Right answer
correct_answers.append(k)
print("Congrats you got it correct\n")
else:
# wrong answer
print("Tough luck, you got that one wrong!")
#final scoreboard
print ("===============================================")
print ("----------------End Game Summary---------------")
time.sleep(0.5)
print ("You got",size_question_list - len(correct_answers),"wrong and ",len(correct_answers)," correct")
time.sleep(3)
print (" !Thanks for playing! ")
print ("===============================================")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers.
To the creator could you please adjust the code so it looks like the code you have in your editor? I cannot read this.
import sys
Binary To Decimal
def bintodec(binnum):
l = len(binnum)
s = binnum
dec = 0
for i in range(0,l):
b = s[l-i-1]
dec = dec + int(b)*(2**i)
return dec
Decimal To Binary
def dectobin(decnum):
if decnum==0:
return "00000000"
bin=""
while decnum>0:
bin = str(decnum%2) + bin
decnum = decnum/2
if len(bin)%8 != 0:
n = 8*(len(bin)/8 + 1) - len(bin)
bin = "0" + bin
return bin
def show_menu():
print ("What do you want to do?")
print ("1. Enter the first number")
print ("2. Enter the second number")
print ("3. Add the two numbers together")
print ("4. Subtract the second number from the first")
print ("5. Exit the program\n")
show_menu()
inp = input()
n1 = ""
n2 = ""
while inp !=5:
if inp=="1":
n1 = str(input("Enter the first number\n"))
print ("The first number chosen is: " + str(n1) + "\n")
show_menu()
if inp=="2":
n2= str(input("Enter the second number\n"))
print ("The first number chosen is: " + str(n1))
print ("The second number chosen is: " + str(n2) +"\n")
show_menu()
if inp=="3":
print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
exit()
if inp=="4":
if bintodec(n2)<bintodec(n1):
print ("For this selection second number should be greater than or equal to first")
else:
print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
exit()
inp = input()
Well, there you go :P Decided to use a switch object because it was interesting. However i'm finding it tough to exit the switch with input '5'
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
def bintodec(binnum):
return int(str(binnum), 2)
def add(first, second):
try:
first = int(first,2)
second = int(second,2)
except:
pass
print('result')
print(int(first) + int(second))
print('')
def sub(first, second):
try:
first = int(first,2)
second = int(second,2)
except:
pass
print('result')
print(int(second) - int(first))
print('')
def show_menu():
while True:
print ("What do you want to do?")
print ("1. Enter the first number")
print ("2. Enter the second number")
print ("3. Add the two numbers together")
print ("4. Subtract the second number from the first")
print ("5. Exit the program\n")
ask_for_input = input('Enter Switch\n')
ask_for_input = int(ask_for_input)
while switch(ask_for_input):
if case(1):
ask_for_1_num = input("Enter the first number\n")
break
if case(2):
ask_for_2_num = input("Enter the second number\n")
break
if case(3):
add(ask_for_1_num, ask_for_2_num)
break
if case(4):
sub(ask_for_1_num, ask_for_2_num)
break
if case(5):
break
break
def main():
show_menu()
if __name__ == '__main__':
main()
Hopefully this is solved now? Might need some work in some places, i'll leave that to you.
Through much confusion as to what you were trying to do this is what i could come up with:
# Binary To Decimal
def bintodec(binnum):
return int(str(binnum), 2)
#Decimal To Binary
def dectobin(x):
return int(bin(x)[2:])
def ask_for_numbers():
number_list = 0
while True:
ask_for_operand = input('Would you like to add or sub')
ask_for_number = input('Please enter a number: ')
try:
if ask_for_operand == 'add':
try:
number_list += bintodec(ask_for_number)
except:
number_list += int(ask_for_number)
print(number_list)
elif ask_for_operand == 'sub':
try:
number_list -= bintodec(ask_for_number)
except:
number_list -= int(ask_for_number)
print(number_list)
else:
return number_list
except ValueError:
print("Not Int or Bin")
def main():
print(ask_for_numbers())
if __name__ == '__main__':
main()
Clearly I had to start again, the decimal to binary function was not needed. The issue with doing it this way is that if i want to add the decimal '10' the function ask_for_numbers() will want to convert that into a binary value. Maybe you can edit this code to figure it out.
I hope this helps :)
I'm making a dart score keeper but it just keeps going round and round. I just need some help as to why this is.
The code:
import time
import sys
from sys import argv
script, name1, name2 = argv
def dartscore():
print "Play from 501 or 301?"
threeorfive = int(raw_input())
if (threeorfive == 501):
def playerone():
startnum1 = threeorfive
while (startnum1 > 0):
print "Ready ", name1,"?"
print "Please enter your score."
minusnum1 = int(raw_input())
startnum1 = startnum1 - minusnum1
playertwo()
if (startnum1 == 0):
print "Well done! You win!"
elif (startnum1 < 0):
print "Sorry but you have entered a wrong score"
playertwo()
def playertwo():
startnum2 = threeorfive
print "Ready ", name2,"?"
print "Please enter your score."
minusnum2 = int(raw_input())
startnum2 = startnum2 - minusnum2
if (startnum2 == 0):
print "Well done! You win!"
print "Unlucky ", name1,". Well played though."
sys.exit()
if (startnum2 < 0):
print "Sorry but you have entered an incorrect score. Please try again"
startnum2 += minusnum2
playerone()
playerone()
dartscore()
Now the two functions playerone() and playertwo() are different because I was trying something with the playerone() function to see if that solved my problem.
Well you have a while(startnum1 > 0):. It seems like startnum1is always bigger then 0. The only way to exit your loop is player 2 has a startnum2 on 0.
Your problem is:
threeorfive = 501
Throughout the entire game, and you begin each of your functions with
startnum = threeorfive
Which means the game 'resets' after both player takes a turn.
A possible fix would be to add global variables:
cumulative1 = 0
cumulative2 = 0
then update cumulative in each iteration:
cumulative1 += minusnum1
cumulative2 += minusnum2
and change your while loop to:
while(threeorfive - cumulative1 > 0)
while(threeorfive - cumulative2 > 0)