This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
JustCall's profile picture

Pressing key within time.

Started by JustCall, 07 October 2015 - 09:26 AM
JustCall #1
Posted 07 October 2015 - 11:26 AM
Hello, I am making a simple minigame that involves the user pressing a certain key within one second.
Unfortunatly, I can't make it work after starting over a few times.

With my current code, you start up the "main" program, and it picks a random program, for example "a", and in the "a" program I want a code that if you press the "a" key within a second, it redirects you to the "correct" program, if you do not, it redirects you to the "failed" program. I already have the "correct" and "failed" programs set up to link to the "main" program.

Can someone help me with the code?
Thanks!
Creator #2
Posted 07 October 2015 - 03:52 PM
in order to achieve that, start a timer for 1 sec. Then pull an event. If the evnt is the timer, the user hasn't pressed the key. However, if the result is a key/char event, then cancel the timer and act accordingly.


timer = os.startTimer(1)
while true do
a,b,c = os.pullEvent()
if a == "timer" then
--stuff
elseif a == "key" then
  os.cancelTimer(timer)
--other stuff
end
timer = os.startTimer(1)
end

Hope I helped.
dan200 #3
Posted 07 October 2015 - 03:54 PM
You should check if the timer event is the *right* timer. Other tabs/coroutines/programs could have started other timers
Creator #4
Posted 07 October 2015 - 04:49 PM
Yup, forgot that one.

Do this:

timer = os.startTimer(1)
while true do
a,b,c = os.pullEvent()
if a == "timer" and b == timer then --this line is changed
--stuff
elseif a == "key" then
  os.cancelTimer(timer)
--other stuff
end
timer = os.startTimer(1)
end

And by the way, Dan200, be sure to check out our absurd guesses in the ooooh pretty thread.
TYKUHN2 #5
Posted 07 October 2015 - 08:53 PM
I also would recommend combining the programs unless you intend to do something that would make such an idea counter-productive. Makes it much easier to manage.
JustCall #6
Posted 08 October 2015 - 03:34 PM
Thanks everyone for replying, Creator's code worked!

TYKUHN, the reason to why I'm doing it my way, is because I can easily ass new keys to press.