How to create counttdown when I show a after a letter? - python

When I show the letter "A" I want a countdown to start from 4. While the countdown is running I want to be able to create a new letter. When I type a new letter, the first countdown should be aborted and the countdown of the new letter should start from 4. How can I do this?
import time
import copy
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('FINISH!!')
sign = input ("Enter text: ")
copySign = copy.deepcopy(sign)
if sign == copySign:
countdown(int(4))

The problem here is interesting and tricky
What I can think of is that you can use threading library to run two separate functions as threads which run simultaneously
In this way you'll not only be able to run a countdown, but also check if user is typing a new letter or not.

Related

I want to take input from user while a timer is running simultaneously

I am creating a sort of a game where the player has to guess a word within a given time limit everything is working accept i dont know how do i run a timer and take input at the same time that too in a loop.
I tried some code but it took input then ran the timer and asked input again so one happened after the other and not simultaneously
How do i fix it
Here is what i tried
import time
def countdown(seconds):
while seconds > 0:
seconds -= 1
time.sleep(1)
seconds = 6
while seconds > 0:
input = ("guess word : ")
countdown(6)
^^ that is only a fraction of my code
Full code here - https://sourceb.in/QYk1D9O2ZT

Creating a sample timer and am greeted by a TypeError

I've been working on a project for around five minutes, and I just got an error:
TypeError: 'str' object is not callable.
Can anyone help me see my error?
from win10toast import ToastNotifier as tst
import time
#timer with notifications
toaster = tst()
#the below input shows how long the timer will last
span_seconds = input('How many seconds will your timer span through? ')
#loops the time until the seconds are up
i = 0
while i < span_seconds():
time.sleep(1)
span_seconds-1
#determines whether the timer is done
if i == span_seconds:
toaster.show_toast('Timer is up!')
span_seconds is a string, as returned from input. You cannot call a string. Nor can you call an int. You don't want to be calling it anyway. You want simply to reference the variable. You can omit the () to do that.
Also, your line span_seconds - 1 doesn't do anything. I'm guessing you're going for something along the lines of span_seconds = span_seconds - 1 (also written as span_seconds -= 1). That line wouldn't accomplish what you're aiming to do, even if written properly, because span_seconds is a string, not an int.
If you change
while i < span_seconds():
span_seconds-1
to
while i < span_seconds:
span_seconds -= 1
as I mention above, and also change
span_seconds = input('How many seconds will your timer span through? ')
to
span_seconds = int(input('How many seconds will your timer span through? '))
converting span_seconds into an int, your code might behave in the way you want it to.

How to force some user input after 10 seconds

I'm a python starter and need some help on a quiz like game.
This is my code:
import time
from threading import Timer
import random as rnd
q = ["q1", "q2", "q3"]
a = ["a1 b1 c1", "a2 b2 c2", "a3 b3 c3"]
ca = ["b", "c", "b"]
points = 0
rand_q = rnd.randint(0, len(q) - 1) # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n") # Asking question and showing answers
time.sleep(0.5) # Little pause between prompts
t = Timer(10, print, ['Time is up!']) # Setting up timer
t.start() # Start timer
start = time.time() # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n") # User input
if answer is ca[rand_q]: # Check if answer is correct
print("Correct answer!")
points = (points + round(10 - time.time() + start, 1)) * 10 # Calculate points
else:
print("Wrong answer!")
t.cancel() # Stop timer
print("Points:", points)
input("Press ENTER to quit")
del q[rand_q] # Removing the question
del a[rand_q] # Removing the answer
del ca[rand_q] # Removing the correct answer
When I run this I can answer questions and get points, but whenver i wait out the timer I get a prompt saying the time is up, but I can still fill in and answer the question.
I want the input to stop working after the 10 seconds, but I can't seem to make this work. Is there any way I can make the timer timeout all previous inputs on top of the "Time is up" prompt.
I've seen more posts like this but they seem outdated and I didn't get them to work.
EDIT: the sleep command doesn't work. It prints a line saying it's too late but you can still enter an answer after. Same for the threading timer. I want to terminate the input command after 10 seconds, but there seems to be no solution for windows.
The problem is that python's input function is blocking, which means the next line of code will not be executed until the user enters some data. A non blocking input is something that a lot of people have been asking for, but the best solution would be for you to create a separate thread and ask the question on there. This question has sort of been answered in this post
This solution will work except the user will still have to press enter at some point to progress:
import time
import threading
fail = False
def time_expired():
print("Too slow!")
fail = True
time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")
if prompt != None and not fail:
print("You answered the question in time!")
time.cancel()
You can do what you intend to do, but it gets very complicated.

Python loop delay without time.sleep()

In an MMO game client, I need to create a loop that will loop 30 times in 30 seconds (1 time every second).
To my greatest disappointment, I discovered that I can not use time.sleep() inside the loop because that causes the game to freeze during the loop.
The loop itself is pretty simple and the only difficulty is how to delay it.
limit = 31
while limit > 0 :
print "%s seconds remaining" % (limit)
limit = limit -1
The python libs exist in the client as .pyc files in a separate folder and I'm hoping that I can avoid messing with them.
Do you think that there is any way to accomplish this delay or is it a dead end?
Your game has a main loop. (Yes, it does.)
Each time through the loop when you go to check state, move the players, redraw the screen, etc., you check the time left on your timer. If at least 1 second has elapsed, you print out your "seconds remaining" quip. If At least 30 seconds has elapsed, you trigger whatever your action is.
You can't do it without blocking or threading unless you are willing to lose precision...
I'd suggest sometime like this, but threading is the correct way to do this...
import time
counter = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### When 1 sec or more has elapsed...
if time.time() - start > 1:
start = time.time()
counter = counter - 1
### This will be updated once per second
print "%s seconds remaining" % counter
### Countdown finished, ending loop
if counter <= 0:
break
or even...
import time
max = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### This will be updated every loop
remaining = max + start - time.time()
print "%s seconds remaining" % int(remaining)
### Countdown finished, ending loop
if remaining <= 0:
break

Pygame simple score system

I have created a simple score system for my pygame. but it's pausing the game. I know it's because of time.sleep but I don't how to sort it out.
The score system is to +100 every 5 seconds while start is true, code:
while start == True:
time.sleep(5)
score = score + 100
Full code with indentation: http://pastebin.com/QLd3YTdJ
code at line : 156-158
Thank you
Instead of using sleep, which stalls the game until time has elapsed, you want to count up an internal timer with the number of seconds which have passed. When you hit 5 seconds, increment the score and then reset the timer.
Something like this:
scoreIncrementTimer = 0
lastFrameTicks = pygame.time.get_ticks()
while start == True:
thisFrameTicks = pygame.time.get_ticks()
ticksSinceLastFrame = thisFrameTicks - lastFrameTicks
lastFrameTicks = thisFrameTicks
scoreIncrementTimer = scoreIncrementTimer + ticksSinceLastFrame
if scoreIncrementTimer > 5000:
score = score + 100
scoreIncrementTimer = 0
This could easily be improved (what if your frame rate is so low there's more than 5 seconds between frames?) but is the general idea. This is commonly called a "delta time" game timer implementation.
If i understand you correctly you dont want the while True: score += 100 loop to block your entire program?
You should solve it by moving the score adding to a seperate function
and use the intervalfunction of APScheduler http://packages.python.org/APScheduler/intervalschedule.html
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Schedule job_function to be called every 5 seconds
#sched.interval_schedule(seconds=5)
def incr_score():
score += 100
This will result in APScheduler creating a thread for you running the function every 5 seconds.
you might need to do some changes to the function to make it work but it should get you started at least :).

Categories