Jump to content

Help with _IsPressed function


Recommended Posts

I'm using AutoIt to write a program that will measure a person's reaction time. The user will be asked to hit a specific random number (0 - 9) on the keyboard, and the program will measure the speed with which the user presses the key.

Here is a function from the program:

Func GetKeyPress($a)
While 1
    If _IsPressed('1b') = 1 Then Return(0) ;1b is ESC
    If _IsPressed($a) = 1 Then Return(1)
Wend
EndFunc

This function works, but it doesn't quite do what I want it to do.

I want the function to return a zero if the user hits the wrong number key, not just if the user hits "Esc". I suppose I could write a long "Select / Case" statement (which would cover all ten possible cases), but I wonder if there is an easier or more elegant way to accomplish this goal.

Thanks.

Link to comment
Share on other sites

:graduated: This is what I made sometime back:

#include <Misc.au3>
$TIMER = TimerInit()
$NEWTIME = 0
While 1
If _GetKeyPress() then 

  msgbox(64, "", "Your reaction time is: " & Round((TimerDiff($TIMER) - $NEWTIME)/1000, 1))
  $NEWTIME = Round(TimerDiff($TIMER), 1)
  EndIf
  WEnd

Func _GetKeyPress()
If NOT _IsPressed('1b') then 
  return 0
  else
  return 1
  EndIf
EndFunc

Will tell you approximate reaction time (upto 1st decimal) everytime the escape key is pressed... -_-

Edited by MKISH

----------------------------------------

:bye: Hey there, was I helpful?

----------------------------------------

My Current OS: Win8 PRO (64-bit); Current AutoIt Version: v3.3.8.1

Link to comment
Share on other sites

Universalist, your suggestions cause the function to return a zero if there is no keypress. I would like the function to wait until there is a keypress. If the key pressed is the correct digit, then the function returns a one. If the key pressed is an incorrect digit, then the function returns a zero.

Link to comment
Share on other sites

Edit: to sum it up i don't think that _IsPressed shud be used in this case, if your looking for elegant way as you stated, there isn't anything more elegant than gui commands (maby mixed with some gdi+ to look cooler).

#include <EditConstants.au3>
#include <Array.au3>
$MaxTime = 3000
GUICreate('',150,200)
$input = GUICtrlCreateInput('',10,10,20,20,$ES_NUMBER)
GUICtrlSetLimit ( -1, 1 , 1 )
$Random = Random(0,9,1)
$lablex = GUICtrlCreateLabel('', 10, 60,140,20)
$lable1 = GUICtrlCreateLabel('', 10, 30,140,20)
$lable2 = GUICtrlCreateLabel('', 10, 90,140,20)
$lable3 = GUICtrlCreateLabel('Waiting Time = '&$MaxTime, 10, 120,140,20)
$lable4 = GUICtrlCreateLabel('Last Time = Unknown', 10, 150,140,20)
GUISetState()
Global $arr[1]
For $x = 5 to 1 Step -1
    GUICtrlSetData($lablex,"Starting in: "&$x)
    Sleep(1000)
Next
GUICtrlSetData($lable1,'Press '&$Random&' fast')
GUICtrlSetData($lablex,'')
$begin = TimerInit()
While 1
    $lastdata = GUICtrlRead($input)
    If $lastdata <> '' Then
        If $lastdata = $Random Then
            $lt = Int(TimerDiff($begin))
            GUICtrlSetData($lable4,'Last Time = '&$lt)
            _ArrayAdd($arr,$lt)
            $Random = Random(0,9,1)
            GUICtrlSetData($input,'')
            GUICtrlSetData($lable1,'Press '&$Random&' fast')
            GUICtrlSetData($lable2,"Correct")
            $MaxTime -= 25
            GUICtrlSetData($lable3,'Waiting Time = '&$MaxTime&'ms')
            SoundPlay(@WindowsDir & 'mediading.wav', 0)
            $begin = TimerInit()
        Else
            wrong()
        EndIf
    Else
        If TimerDiff($begin) > $MaxTime Then
            wrong()
        EndIf
    EndIf
WEnd
Func wrong()
    SoundPlay(@WindowsDir & 'mediachord.wav', 0)
    GUICtrlSetData($input,'')
    GUICtrlSetData($lable2,'Wrong')
    MsgBox(0,'TheEnd','2 Slow')
    $arr[0] = UBound($arr) - 1
    _ArrayDisplay($arr)
    Exit
EndFunc
Edited by bogQ

TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 
Link to comment
Share on other sites

  • Moderators

AlexChernavsky,

Here is how I might do it: ;)

#include <Misc.au3>

Local $hDLL = DllOpen("user32.dll")

; Declare a flag
$fCorrect = False

; Get a random key value 0-9
$iMatch = Random(0, 9, 1)

; Announce the key to press
SplashTextOn("Hit a Key", "Hit key " & $iMatch & " now!", 200, 150, Default, Default,32,  Default, 24)

; Take a timestamp
$iBegin = TimerInit()

; Wait for a key to be pressed
While 1

    ; Run through the 0-9 keys and see which is pressed
    For $i = 0 To 9
        ; Convert the counter to the keycode
        $iCode = String(30 + $i)
        ; If one of the keys is pressed
        If _IsPressed($iCode, $hDLL) Then
            ; Get the reaction time
            $nDelay = TimerDiff($iBegin)
            ; Was it the correct key?
            If $iMatch = $i Then
                ; Set the flag
                $fCorrect = True
            EndIf
            ; And break out of the loops
            ExitLoop 2
        EndIf
    Next

    ; Check we are not waiting too long
    If TimerDiff($iBegin) > 10 * 1000 Then
        DllClose($hDLL)
        SplashOff()
        MsgBox(0, "Error", "How long do you want?")
        Exit
    EndIf

WEnd

DllClose($hDLL)

; Remove the splash scren
SplashOff()

; Announce the result
If $fCorrect Then
    MsgBox(0, "Correct", "Reaction Time = " & $nDelay / 1000 & "secs")
Else
    MsgBox(0, "Error", "Incorrect key")
EndIf

Please ask if you have any questions. :)

And to anyone reading,

This is a good example of a "how to check for a few keys being pressed" script which is quite legal as explained here. Checking in this manner for many more keys than this would not be acceptable on the forum - as well as being very inefficient. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

And to anyone reading,

... script which is quite legal as explained.

darn, so close to report a gm :P

joking ofc ;)

TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 
Link to comment
Share on other sites

  • Moderators

bogQ,

so close to report

Which is why I put that rider in the post! :D

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I tried Melba23's example, and it seems to work. Thank you! I will try the others later and try to learn from them.

I do have one question for Melba23. When I hit a key, the same key seems to add a character to the end of the script. So, for example, if I hit an "8", an "8" then appears after EndIf, like this: EndIf8. Is there a way to stop it from doing that, by clearing the keyboard buffer (or some such thing)?

Thanks go out to everyone for your help. I appreciate it, and I'm having fun learning AutoIt.

Link to comment
Share on other sites

You can try with HotKeySet() to block input from that key, but itl be fun if user press something that you did not predict.

_IsPressed() dont stop key input that is why i did tell you that i don't think that _IsPressed shud be used in this case and posted gui example.

Edited by bogQ

TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 
Link to comment
Share on other sites

I came up with an alternative, using the GuiSetAccelerators. In this example I am using the F1-F9 keys, because I am using a laptop, but you can replace F by NUMPAD. I like this method because you can call 2 different functions for each event.

Opt ( "GuiOnEventMode" , 1 )

$Gui = GUICreate ( "Speed Test" , 500 , 200 )
$Edit = GUICtrlCreateEdit ( "" , 5 , 5 , 480 , 180 )
GUISetOnEvent ( $GUI_EVENT_CLOSE , "_Exit" )
GUISetState()

;Create some dummies to call the function
$DummyGoodKey = GUICtrlCreateDummy()
GUICtrlSetOnEvent ( $DummyGoodKey , "_GoodKey" )
$DummyBadKey = GUICtrlCreateDummy()
GUICtrlSetOnEvent ( $DummyBadKey , "_BadKey" )

$RndKey = Random ( 1 , 9 , 1 ) ;Random keys F1-F9
_SetGoodKey ( $RndKey )
GUICtrlSetData ( $Edit , "Press the key : F" & $RndKey )
$Timer = TimerInit()

While 1
Sleep (10)
WEnd

Func _GoodKey()
GUICtrlSetData ( $Edit , "Good Key pressed!" & @CRLF & "Your Time: " & TimerDiff ( $Timer ) / 1000 & " s" & @CRLF )
EndFunc

Func _BadKey()
GUICtrlSetData ( $Edit , "Wrong key pressed!" & @CRLF )
EndFunc

Func _SetGoodKey ( $iGoodKey )
Local $aAccelerators[10][2]
For $i = 0 To 9
If $i = $iGoodKey Then
$aAccelerators[$i][0] = "{F" & String ($i) & "}" ;You can replace "F" with "NUMPAD"
$aAccelerators[$i][1] = $DummyGoodKey
Else
$aAccelerators[$i][0] = "{F" & String( $i) & "}" ;You can replace "F" with "NUMPAD"
$aAccelerators[$i][1] = $DummyBadKey
EndIf
Next
Return GUISetAccelerators ( $aAccelerators , $Gui )
EndFunc

Func _Exit()
Exit
EndFunc
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...