I've made a game that runs in the command line. There is a timer thread and a game thread, once the timer runs out the game thread does end. However, if the user still hasn't made an input they are still able to. Is there a way to just cancel the input function? Here's the code (excuse the messiness):
The timer code
done = False
timeLeft = 180
# 3 minute timer to finish the game
def timer():
global timeLeft
while timeLeft > 0:
sleep(1)
timeLeft -= 1
if done:
break
else:
print('\n\nTimes up!')
finishedGame()
The game loop within game()
while gameBoard.busts < 3 and len(shuffledDeck) > 0:
topCard = shuffledDeck[0]
print(topCard)
# Asks where to place the top card and removes it from deck
chosenColumn = int(input('\nWhich column would you like to add this card to?'))
if chosenColumn == 1:
gameBoard.col1.addCard(topCard)
checkColumn(gameBoard.col1)
if chosenColumn == 2:
gameBoard.col2.addCard(topCard)
checkColumn(gameBoard.col2)
if chosenColumn == 3:
gameBoard.col3.addCard(topCard)
checkColumn(gameBoard.col3)
if chosenColumn == 4:
gameBoard.col4.addCard(topCard)
checkColumn(gameBoard.col4)
shuffledDeck.pop(0)
if timeLeft == 0:
break
os.system('cls' if os.name == 'nt' else 'clear')
gameBoard.output()
else:
finishedGame()
Creation of the threads
if __name__ =='__main__':
# Creates 2 threads to run alonside each other
# Timer thread to run in background
t1 = Thread(target=timer)
# Game thread to run the actual game
t2 = Thread(target=game)
t1.start()
t2.start()
CodePudding user response:
Guys don't just start downvoting his question he was quite clear on what he needed your just going to start turning people away from stack overflow. Dillan I found this. https://stackoverflow.com/a/62611967/14987438 and if you hate linkss then here's the code.
from threading import Thread
import time
import os
answer = None
def ask():
global start_time, answer
start_time = time.time()
answer = input("Enter a number:\n")
time.sleep(0.001)
def timing():
time_limit = 5
while True:
time_taken = time.time() - start_time
if answer is not None:
print(f"You took {time_taken} seconds to enter a number.")
os._exit(1)
if time_taken > time_limit:
print("Time's up !!! \n"
f"You took {time_taken} seconds.")
os._exit(1)
time.sleep(0.001)
t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()