Page 1 of 1

[Console]How to realise a countdown?

Posted: Mon May 22, 2006 5:44 pm
by PureBaser
Hi there!

Can anyone tell me, how I can build a Countdown in my Console-Programm. The Background is, that the Player has a certain time to answer a Input()-Question, after the time is up, he's lose. And it is possible to make the Countdown visible in seconds while at the same moment the player can answer?

Posted: Mon May 22, 2006 6:35 pm
by netmaestro
OK, probably somewhat buggy and unpolished as yet, but this covers most of the bases:

Code: Select all

Global startloc 
Global threadactive 

Procedure TimeOut(t) 
  time=ElapsedMilliseconds() 
  timestr.s = Str(t - (ElapsedMilliseconds()-time) / 1000) 
  ConsoleLocate(40,5) 
  Print(timestr) 
  ConsoleLocate(startloc,5) 
  Repeat 
    If threadactive 
      newtimestr.s = Str(t - (ElapsedMilliseconds()-time) / 1000) 
      If newtimestr <> timestr 
        timestr = newtimestr 
        ConsoleLocate(40,5) 
        Print(newtimestr+"  ") 
        ConsoleLocate(startloc,5) 
      EndIf 
      If (ElapsedMilliseconds()-time) / 1000 >= t 
        keybd_event_(#VK_RETURN,0,0,0) 
        keybd_event_(#VK_RETURN,0,#KEYEVENTF_KEYUP,0) 
        threadactive = #False 
      EndIf 
      Delay(1) 
    EndIf 
  Until threadactive = #False 
EndProcedure 

OpenConsole() 
EnableGraphicalConsole(1) 
ConsoleLocate(5,5) 
Print("Enter your name: ") 
threadactive = #True 
CreateThread(@Timeout(),10) 
startloc = 22 

Repeat 
  Delay(1)
  inputstr.s = Inkey() 
  If inputstr <> "" 
    If inputstr = Chr(8) 
      startloc - 1 
      ConsoleLocate(startloc,5) 
      Print(" ") 
      outstr.s = Left(outstr,Len(outstr)-1) 
    Else 
      ConsoleLocate(startloc,5) 
      If inputstr<>Chr(13) 
        outstr.s + inputstr 
        Print(inputstr) 
      Else 
        ConsoleLocate(40,5) 
        Print("  ") 
        ConsoleLocate(18,9) 
        threadactive = #False 
      EndIf 
      startloc + 1 
    EndIf 
  EndIf 
Until inputstr = Chr(13) 

ConsoleLocate(5, 7) 
If outstr = "" 
  PrintN("Timeout!") 
Else 
  PrintN("You entered: "+outstr) 
EndIf 
PrintN("") 
Print("<any key to quit>") 
Input()

Posted: Mon May 22, 2006 7:05 pm
by netmaestro
oops - added a delay to the main loop. very important!

Posted: Mon May 22, 2006 7:46 pm
by josku_x
@netmaestro: your code crashes my computer if I start to flood the program with characters, also some weird characters are shown after the user input (something like a '%' character after your text)

Posted: Mon May 22, 2006 7:51 pm
by netmaestro
It's just a skeleton to show the method. To make it into a real program you'd want to filter the InKey() values for a-z, A-Z, 0-9 and not accept anything else. And you'd limit the length. It's a good starting place, that's all it's intended for.

Posted: Wed May 24, 2006 2:46 pm
by PureBaser
Thanks! :D