How can I immediately interrupt a while loop, or refactor my logic?

Ask gaming related questions (AHK v1.1 and older)
rzjnzk
Posts: 2
Joined: 23 Nov 2017, 09:45
Contact:

How can I immediately interrupt a while loop, or refactor my logic?

Post by rzjnzk » 21 Jan 2022, 01:30

I'm trying to write an auto sprint script for the game The Forest, however, I need to hold the shift key down for some duration, then release and wait for stamina to regenerate before pressing once again. I would rather not have to wait for this cycle to complete before exiting the loop and so I want a way to immediately end the hotkeys logic when I press `W` and/or `Shift`. Currently this logic will end the loop after the current iteration, however, when I then wish to use 'W' to walk forward ingame my character appears to be making minute steps.

Code: Select all

#SingleInstance Force

; #MaxThreads 2

#IfWinActive ahk_exe TheForest.exe

global stop = 0

*$W::
    Send, {W}
    stop = 1
    Return

*$Shift::
    Send, %A_ThisHotkey%
    KeyWait, %A_ThisHotkey%, D T0.10
    
    ; If ErrorLevel is non-zero if the above KeyWait timed out. You only pressed and released the hotkey once.
    if (!stop)
    {
        stop = 0
        Send, {W down}

        while (!stop)
        {
            Send, {Shift down}
            Send, {Shift down}
            Sleep, 5000
            Send, {Shift up}
            Sleep 3125
        }
    }

    Return
EDIT:

Working Version (SOLVED)

Code: Select all

; NAME
;     the-forest-auto-sprint.ahk
;
; DESCRIPTION
;     Auto-sprint script for 'The Forest' that holds shift at set time intervals.
;
; AUTHORS
;     Copyright (c) Robert Zack Jaidyn Norris-Karr <[email protected]> <https://github.com/rzjnzk>
;
; NOTES
;     Main Repository: 

#SingleInstance Force

#IfWinActive ahk_exe TheForest.exe

*$Shift::
    Send {Shift}
    if (A_ThisHotkey == A_PriorHotkey && A_TimeSincePriorHotkey < 300)
    {
        Send, {W down}

        loop
        {
            Send, {Shift down}
            Send, {Shift down}

            KeyWait, Shift, D T5

            if (!ErrorLevel)
            {
                Break
            }

            Send, {Shift up}

            KeyWait, Shift, D T3.125

            if (!ErrorLevel)
            {
                Break
            }
        }

        Send {W up}
        Send {Shift up}
    }

    Return

Return to “Gaming Help (v1)”