Adding a timer to the while loop - python

The program I made is like monkey typer and I want to implement a timer into my code but I don't know-how. If I make another while loop it runs separately all I want to do is have a timer running at the same time as you are inputting the words. Where do I implement the timer() the while loop? New while loop?
# imports
from words import words
import random
import time
# variables
score = 0
max_score = 10
def timer(length):
while True:
print(length)
length = length - 1
time.sleep(1)
if timer == 0:
print('Game completed \nFinal score, ', score)
break
while True:
random_word = random.choice(words)
print('\n', random_word)
user = input(':')
# if correct
if user == random_word:
score = score + 1
print('Correct!\n', 'Score,', score)
# if incorrect
if user != random_word:
print('Incorrect!\n', 'Score,', score)
score = score - 1
if score < 0:
score = 0
# made by Jack Winton

You could try using multithreading or multiprocessing to create a timer, have one thread or process working on the code and another thread running the timer. Another option is to use time = time.time() then once the loop is finished add an end = time.time() and then do overall_time = start - end but I think you are trying to do a countdown, not a timer.

Related

How do I Run a Background Timer for Each Prompt in My Word Game?

I'm making an unoriginal game for a first project that just runs in my python terminal. The user is randomly given a set of 2-3 letters and the user has to come up with a real word (checked by the Webster dictionary) that contains the given set of letters within 5 seconds. For example, if the game generates "le" the user can input "elephant" within 5 seconds as a correct word and gives them a point.
The problem is that I can't seem to implement the 5 second timer function to run in the back for every time a prompt is given without messing up some other part or running into another problem. I've looked into threading and can't seem to make use of it.
Here is the code for the main game:
from letters import letter_sets_list
fhand = open("words_dictionary.json")
data = fhand.read()
global score
score = int(0)
game_over = False
while game_over is False:
import random
random_letters = random.choice(letter_sets_list)
print('Word that contains:', random_letters)
answer = input("Type a word:")
if answer in data and random_letters in answer:
score += 1
print("nice one")
else:
game_over = True
print("Game Over \n Score:", score)
fhand.close()
exit()
Here is the timer function I found off YouTube and tried to implement:
def countdown():
global my_timer
my_timer = int(5)
for x in range(5):
my_timer -= 1
sleep(1)
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
Take a look at that. Especially check if that will work for you:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")
Edit: I tried to implement code from my previous answer to your code but with a little different approach:
import time, threading
#from letters import letter_sets_list
#import random
#fhand = open("words_dictionary.json")
#data = fhand.read()
data = ["answer"]
answer = [None]
random_letters = [None]
global score
score = int(0)
game_over = False
x = 0
def game(answer, random_letters):
#random_letters = random.choice(letter_sets_list)
print('Word that contains:', random_letters)
while True:
answer[0] = input("Type a word: ")
mythread = threading.Thread(target=game, args=(answer, random_letters))
mythread.daemon = True
mythread.start()
for increment in range(5):
time.sleep(1)
if answer[0] in data: # and random_letters in answer
score += 1
print("Good answer")
x = 1
break
if x != 1:
print("\nTime is up")
else:
x = 0
game_over = True
In this approach I didnt use time.sleep() inside threaded function but outside of it which helps with killing it. Also i assumed that if your answer is incorrect you would like to have another chance to answer untill time is up or answer is correct so I just used while loop in threaded function. The code is quite simple so I think if you spend a little time analysing your parts of the code you will figure it out.
Some parts of the code I didn't use as I dont have access to your json files ect., but if I understand correctly what you're trying to do, it shoud work. Also check how will behave your kernel. In my case sometimes it shows some problems but my PC is not the best and so it might be only problem with RAM or other part of my computer as it happens quite often with my projects.

How do i do some stuff and count time in parallel in python?

I want my code to take some integers for some time (e.g. 10 seconds) and to count and print time every second. So it prints time permanently and i enter some numbers whenever i want. Maybe i should use async functions?
def accepting_bets():
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
def main():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
accepting_bets()
if i == 0:
break
print(list_of_bets)
You can move the timing code to a different thread.
I would recommend researching about multi-threading in Python if you aren't aware about it.
import threading
import time
def countTime():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
if i == 0:
break
print(list_of_bets)
thread1 = threading.Thread(target=countTime)
thread1.start()
# while you want to get the input
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
The countTime function will keep on running on another thread, and will not be paused by the input statement

How do I iterate through a countdown timer while checking for user input simultaneously?

I am trying to code a chess timer in which there are two timers counting down alternatingly. Only one timer runs at a time, and when a certain input is given by the user, which I am using keyboard.is_pressed("some_key") for, one timer pauses and the other begins counting down and vice versa. My problem is that to countdown by intervals of 1 second, I am using time.sleep(1) and the program will not receive user input during this time, so unless the user gives input on exactly the 1 second mark, nothing happens. How can I make the countdown process and the checking for user input process run at the same time?
Here is the code:
import time
import keyboard
def timers(t1, t2):
pause = True
while t1 or t2:
if pause:
while pause:
mins1 = t1 // 60
secs1 = t1 % 60
timer1 = '{:02d}:{:02d}'.format(mins1, secs1)
print("Timer1: ", timer1)
time.sleep(1)
t1 -= 1
if keyboard.is_pressed("w"):
pause = False
break
else:
continue
else:
while not pause:
mins2 = t2 // 60
secs2 = t2 % 60
timer2 = '{:02d}:{:02d}'.format(mins2, secs2)
print("Timer2: ", timer2)
time.sleep(1)
t2 -= 1
if keyboard.is_pressed("w"):
pause = True
break
print("Beep")
tWhite = int(input("Enter the time in seconds for White: "))
tBlack = int(input("Enter the time in seconds for Black: "))
timers(tWhite, tBlack)

How to fix a for loop when it doesn't run through the whole code

I am studying Python and now I'm doing a small project on my own. The for loop in the second function is not run through the whole code. When I run the code I get just the last element of the dictionary.
In order to solve it I have tried to use while but I got the same answer.
def enter_task():
global num_task
num_task = int(input("Please, enter number of tasks: "))
calendar = {}
for i in range(0, num_task):
global task
task=input("Please, enter task: ")
set_time = input("Please, enter time for {}: ". format(task))
calendar[task] = set_time
print(calendar)
def conclusion():
count = 0
for i in range(0, num_task):
is_done = input("Is task {} completed? Enter Yes/No: ".format(task))
if is_done == "yes":
count += 1
return count
print('Nicely done. {} of {} tasks were completed today'. format(count, num_task))
When I call conclusion, the input is_done is shown just once and the task is equal to the last task I typed in the function enter_task. Also the count is not counting and the statement is not printed. The input is_done should appear as many times as nun_task and each time with a different task on it.

I am testing out threading.Time in this little game I made, but it keeps overlapping

import time
from threading import Timer
from random import randint
print("Every wrong answer is a 3s delay; you have 30s")
end = False
def lose():
print(end)
print("Time up!")
time.sleep(1)
print("Score is",pts,", with",wrong,"wrong answers.")
time.sleep(1)
input("enter to quit")
quit()
timer = Timer(10,lose)
timer.start()
pts = 0
wrong = 0
while end == False:
a = randint(5,50)
b = randint(5,50)
print(a,"+",b)
ans = input()
if ans.isnumeric():
ans = int(ans)
if ans == a+b:
print("correct")
pts = pts+1
else:
print("wrong,",a+b)
wrong = wrong+1
print("delay")
time.sleep(3)
print("delay end")
print("")
When the timer finishes, the loop overlaps the 'lose' function, and it messes up on the line like this:
Time up!
45 + 10
55
Score iscorrect
3
, with29 0+ wrong answers.37
enter to quitwrong,p
66
delay
How do I fix this issue?
Sorry if this question has already been answered, but I want to know.
Ideally, you should probably avoid using threads altogether, as mentioned in the comments.
However, if you are going to use threads, consider using a mutex to ensure that multiple threads are not trying to write to stdout at the same time.
For example:
# setup at the beginning:
from threading import Thread, Lock
mutex = Lock()
# surrounding each print statement:
mutex.acquire()
try:
print('text')
finally:
mutex.release()

Categories