2

I'm trying to code a boggle game in console. I want to ask for multiple user inputs for different words until game time runs out, and every word input is stored to a list. Initially the code looks like this:

import time

words = []
time_limit = 5
start_time = time.time()
while time.time() - start_time < time_limit:
    word = input("Enter word: ")
    words.append(word)

But if you try the code above, the input functionality persists beyond the time limit and only breaks out of the loop when the user supplies an input. The program is supposed to exit the loop (and stops asking for input) when the time limit is reached and not being dependent with user actions.

Although in actuality I may have to use threading like so:

import time
import threading

def countdown(time_limit):
    global on_play
    start = time.time()
    while time.time() - start < time_limit:
        pass
    on_play = False

on_play = True
words = []
time_limit = 5
timer = threading.Thread(target=countdown, args=(time_limit,))
timer.start()
start_time = time.time()
while on_play:
    word = input("Enter word: ")
    words.append(word)

Even then, the problem stays the same.

Here are few references/approaches I've tried but they don't particularly "exits" the loop/input when time runs out:

Use of msvcrt module as answered from Time-Limited Input? In addition to this not exiting the loop/input, it seems msvcrt only works on Windows and not cross-platform.

Use of sys.stdin Based from https://www.geeksforgeeks.org/take-input-from-stdin-in-python/, it calls input function internally, which poses the same issue.

Other references They mostly resemble my own approach.

Jobo Fernandez
  • 905
  • 4
  • 13
  • Maybe you need to split the process into two threads like [this](https://stackoverflow.com/a/62611967). – jack Oct 12 '22 at 15:30
  • On second thought, os.exit or os._exit may not be viable as they would stop executing the rest of the commands and game loop and the entirety of the program. – Jobo Fernandez Oct 12 '22 at 16:23
  • Wow. This problem is harder than I first thought. `input()` is blocking and therefore will screw up your timing. I found [one solution](https://stackoverflow.com/a/19655992/9705687) that is promising and relies on reading one character at a time with `sys.stdin.read(1)`. But that solution is wonky with the display and I'm not sure that backspace and/or arrow keys will work correctly. I wonder if there is a way to make [curses](https://docs.python.org/3/howto/curses.html) work. Curses has the `endwin()` function that you might be able to use to kill the session. – bfris Oct 12 '22 at 19:01

0 Answers0