I'm trying to code a kind of simple video game where there are two kind of players:

  • Human Players: They enter an keyboard input
  • CPU Players: A random input is calculated

For Human Players there is a T round time and a T' input entering time. Let's say, if T=20 and T'=5, a player has 20 seconds to start typing, but only 5 seconds of typing time. So, if the player starts typing at T=10, will only be able to type those T'=5 seconds until T=15.

Just so you know, I'm using Typescript, and I had something like this in mind:

while (!gameOver) {
   // do some stuff like knowing who's player turn is it

   var enteredInput;

   if (player.isHuman()) {
      enteredInput = captureKeyboardInputsFor(seconds);
   } else {
      enteredInput = calculateRandomCPUPlayerInput();

   // process input & do actions

What I would like to achieve here is a kind of synchronous typing process, I have the game logic well defined in mind, but I'm trying to figure out how can I do this keeping my loop game synchronous (as the players play in turns), using TypeScript.

I would really appreciate any kind of guidance, alternatives or ideas of possible ways of solving my concerns.

  • You are going to have to rethink your approach to be more event driven. JS is single-threaded. While that while loop is running, keystrokes won't be registered and events won't fire.
    – John Wu
    Mar 9, 2017 at 23:34
  • @JohnWu you are totally right! But in this case this is just a very concrete scenario I have to get through and I have to try to do it "synchronously". I found an approximation that will do the trick: instead of having a loop, I will use recursion to achieve a synchronous flow. Thanks for your point, anyway! Mar 9, 2017 at 23:44
  • At this point I am not sure what your question is, specifically.
    – John Wu
    Mar 9, 2017 at 23:46
  • I wanted enteredInput = captureKeyboardInputsFor(seconds); to be blocking, because players play in turns, so if it's let's say PlayerA's turn, PlayerB can't enter anything until his turn comes. Mar 9, 2017 at 23:51
  • I just told you it's not possible. You can't have code that is blocking and keyboard entry at the same time.
    – John Wu
    Mar 10, 2017 at 0:08


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.