How to set a pop up time limit in python? [duplicate] - python

This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 9 years ago.
I want to have a time limit in order to enter the input in the following code. In other words, there should be a timer tracking the time and if it exceeds the limit, the code should print out a message like "Game over" automatically without hitting any key. it is a sort of pop-up.
def human(player, panel):
print print_panel(panel)
print 'Your Turn! , Hint: "23" means go to row No.2 column No.3/nYou got 1 min to move.'
start_time = time.time()
end_time = start_time + 60
while True :
move = raw_input('> ')
if move and check(int(move), player, panel):
return int(move)
else:
if (time.time() < end_time):
print 'Wrong move >> please try again.'
else:
print "Game over"
return panel, score(BLACK, panel)
break
the other question is almost the same but the answer is not what I am looking for. I want the code to return a message when the time is over without hitting "ENTER".

The simplest way is to use the curses module. You'll want to set nodelay(1), and poll for input. http://docs.python.org/2/howto/curses.html#user-input

Related

How to use the code in a loop after one part of the code is completed? [duplicate]

This question already has answers here:
How to loop back to the beginning of the code on Python 3.7
(3 answers)
Closed 3 years ago.
I am using python 3, and I want to know how to return the code to the second linex = input ('Enter your first name here: ') after completing the if or elif conditions
I have searched other stack overflow answers but to no avail
print ("hello world")
x = input ('Enter your first name here: ')
if len(x) > 10:
print ("You have a long name")
elif:
print ("You have a short name")
Replace elif with else
The elif is short for else if. It allows us to check for multiple expressions. You aren't checking anything hence it should be replaced with else
Plus by doing that you fix a syntax error
elif:
^
SyntaxError: invalid syntax
This is not a valid Python statement.
edit:
if you want to repeat the question askeed to the user use a while loop:
in your case:
while True:
x = input ('Enter your first name here: ')
if len(x) > 10:
print ("You have a long name")
else:
print ("You have a short name")
This will work forever unless you kill it via a Task Manager or interrupt it using the keyboard.
You can use loop statement to return the second check condition again. Please refer this link for loops in python
for example of using while loop
answer = None
while True:
answer = raw_input("Do you like pie?")
if answer in ("yes", "no"): break
print "That is not a yes or a no"
it works like goto statement. you can use break or continue statement to stop or continue execution of loop.

My function is too long. In order to pass class I need < 18 lines

So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.

Creating a multiple user countdown counter (Python)

I was wondering if someone can point me in the right direction of a basic script.
This is for a game I created and wanted to create a countdown script to go along with it.
I want be able to have 4 users in which the program will first will ask for their name. After that each user will take turns entering their score starting at 100 and decreasing based on their input. Once they hit zero they win. Once the first person hits 0 the others will have a chance to as well until the end of the round. Each 4 inputs will be considered 1 round.
There will be a lot more to the game but I just need the start. I am new to Python but the easiest way for me to learn is to start off on a working script
Thanks!
Are you looking for something like this?
import cmd
number_users = 4
number_rounds = 10 # or whatever
user_names = [None]*number_users
user_scores = [None]*number_users
for i in range(number_users):
print("Enter name for user #{}: ".format(i+1))
user_names[i] = input()
user_scores[i] = 100
for round_number in range(number_rounds):
print(" --- ROUND {} ---".format(round_number+1))
for i in range(number_users):
print("{}, Enter your score: ".format(user_names[i]))
user_scores[i] = input()
print("--- Scores for Round {} ---".format(round_number+1))
for i in range(number_users):
print("{} : {}".format(user_names[i], user_scores[i]))
print("Done")

Implementing a timer(countdown) that runs pararell with the game logic [duplicate]

This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 6 years ago.
I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.
At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.
Here is an idea with pseudo code:
if (answer = wrong || time = 0)
lost...
if you want to check if the user took to long when he answered you can use the time module to calculate the diffrence:
start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
lose()
if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:
timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
lose()

While not asking twice for the input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
scenario2(outcome) function calls sget_choice3 one so it either prints an outcome based on the users choice.
I want function to loop and ask for input twice if the Users selection is 0 (correct one is 1 and 0 is just a branch of it).
s2option_list3 =['Try to force it', 'Examine the door']
def sget_choice3(s2option_list3):
i = -1
while i <= 0:
print s2option_list3
choice3 = raw_input("> ")
for i, opt in enumerate(s2option_list3):
if opt in choice3:
i = i + 1
return i
else:
i = i + 2
return i
print "You need to select one of the given actions"
def scenario2_exit(outcome):
print outcome
choice = outcomes[0]
if outcome in choice:
print "conversation"
res3 = sget_choice3(s2option_list3)
if res3 == 0:
print "You try to force it but without any luck. However you do notice a little button on the left corner. "
else:
print "A small panel comes out, seems to be requesting a code. "
print "conversation"
else:
print "conversation"
Your issue appears to be in this line:
for i, opt in enumerate(s2option_list3):
When you use enumerate like that, it is overwriting your value for i (-1 at the time) with the index of the enumeration (0 for the first option and 1 for the second). I'm not sure why you are trying to use the enumeration at all.
Without giving you too much advice on how to restructure your program, a simple fix could be something like:
for opt in s2option_list3:

Categories

Resources