如何使用输入功能运行另一行代码

问题描述 投票:0回答:1

我做了一个井字棋游戏,并在游戏回合中添加了时间限制。 我的问题是如何让玩家看到剩余时间。我不知道如何运行不同的代码行,例如同时使用输入功能显示剩余时间的文本。

这是我当前的代码: (该函数是类的一部分)

from inputimeout import inputimeout, TimeoutOccurred

def play_turn(self):
    while True:
        try:
            choice = int(inputimeout(prompt=f"{self.players[self.current_player].name}, choose a move: ", timeout=5))
            if 1 <= int(choice) <= 9 and self.board.update_board(choice, self.players[self.current_player].symbol):
                break
            else:
                print("Invalid move,try again")
        except TimeoutOccurred:
            print("Timed out!!")
            time.sleep(2)
            return
        except ValueError:
            print("Please enter a number between 1 and 9")
python input
1个回答
0
投票

您可以使用 python 线程来做到这一点。 您可以使用这 2 个函数(countdownTimer 和 getUserInputTimeout)通过输入实现威胁。

例如:

import threading
import time
from inputimeout import inputimeout, TimeoutOccurred

def countdownTimer(timeout, timer_event):
    for i in range(timeout, 0, -1):
        if timer_event.is_set():
            break  # Exit the loop if the timer event is set
        time.sleep(1)

def getUserInputTimeout(prompt, timeout):
    # Create an event to signal the timer thread to stop
    timer_event = threading.Event()

    # Start the countdown timer in a separate thread
    timer_thread = threading.Thread(target=countdownTimer, args=(timeout, timer_event))
    timer_thread.daemon = True  # Set the timer thread as a daemon thread
    timer_thread.start()

    try:
        # Loop to wait for user input until timeout or input received
        start_time = time.time()
        while True:
            remaining_time = timeout - int(time.time() - start_time)
            if remaining_time <= 0:
                raise TimeoutOccurred
            print(f"\rTime left: {remaining_time} seconds: ", end='', flush=True)
            try:
                choice = inputimeout(prompt='', timeout=1)
                return choice
            except TimeoutOccurred:
                pass
    except TimeoutOccurred:
        print("\nTimeout. No input received.")
    finally:
        timer_event.set()
        timer_thread.join()


timeout_duration = 5

user_input = getUserInputTimeout(prompt="Answer: ", timeout=timeout_duration)
if user_input is not None:
    print(f"\nResponse: {user_input}")

执行:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.