1 (изменено: Indomito, 2014-07-09 06:01:11)

Тема: AHK: Saints Row The Third (готовый скрипт)

Не большая автоматизация для игры Saints Row The Third

По сути она касается управления машиной и другими средствами передвижения. В игре есть конечно круиз-режим, но он обладает недостатками и я постарался всё исправить.

Осторожно, т.е. аккуратно.
1. В игре намертво прописаны некоторые клавиши, можно было их вынести в блок инициализации, но я не стал.
Просто достаточно поправить два блока

+ Включение перехвата
lMainTHQon2:
;Hotkey - creates, modifies, enables, or disables a hotkey while the script is running.
;Here is a general rule records - Hotkey, KeyName [, Label, Options]
;Hotkey command syntax rules are described in the programming language AutoHotkey.
         Hotkey, WheelUp,                   lGearInc,              On
         Hotkey, WheelDown,                 lGearDec,            On
         Hotkey, PgUp,                lMaxGear,         On         
     Hotkey, PgDn,                lMinGear,           On         
       Hotkey, Up,                           lUp,                         On
       Hotkey, Down,                          lDown,                     On
     Hotkey, Left,                            lLeft,                     On
     Hotkey, Right,                        lRight,                 On
       Hotkey, End,                 lToggleGearBox,    On
       Hotkey, Home,                lCorrectorYaw,    On    
       Hotkey, RCtrl,               lSwitchEngine,    On     
 fnPlaySoundTHQ(iSoundStart)
 fSoundPlay := false
 gosub lSetTimerOn
return
+ Выключение перехвата
lMainTHQoff2:
  gosub lSetTimerOff
;When you turn off enough to indicate Cycled key, but clearer and less chance go wrong.
         Hotkey, WheelUp,                   lGearInc,              Off
         Hotkey, WheelDown,                 lGearDec,            Off
         Hotkey, PgUp,                lMaxGear,         Off         
     Hotkey, PgDn,                lMinGear,           Off         
       Hotkey, Up,                           lUp,                         Off
       Hotkey, Down,                          lDown,                     Off
     Hotkey, Left,                            lLeft,                     Off
     Hotkey, Right,                        lRight,                 Off
       Hotkey, End,                 lToggleGearBox,    Off
       Hotkey, Home,                lCorrectorYaw,    Off    
       Hotkey, RCtrl,               lSwitchEngine,    Off         
if (!fSoundPlay)
         {    
          fnPlaySoundTHQ(iSoundStop)
            fSoundPlay := true
         }
return

2. Клавиши LShift  RShift TAB ESC Enter / и стрелки так же прописаны "намертво", но всё исправляется.
Клавиша / связана с перезарядкой оружия, т.е. она переделана, а клавиша Enter позволяет мгновенно выпрыгнуть из машины в независимости от её текущей скорости.

+ Вот общий блок
;The script is paired directives - #UseHook, On|Off this means that the ON/OFF hook the keyboard and key within directives may call itself.
#UseHook, On

;Correction reloading weapons, ie "/" key (scan code of the key, it is the 8th, it's not a mouse problem or a system)
sc35:: 
 Send, {sc35 Down}
 KeyWait, % A_ThisHotkey
 Send, {sc35 Up}
return

;These keys access the game menu and we disable functions the main part the script.

Enter::
 if ((vRSh) && (iGear>=1)) ;When leaving the car do fast and smooth braking, almost on the spot, at any speed.
      {
        iGearTmp := iGear 
        gosub lMinGear
        Send, {Down Down}
         loop  %iGearTmp%
          Sleep %td30_Sleep%
        Send, {Down Up} 
      }
  Send, {Enter Down}
  KeyWait, % A_ThisHotkey
  Send, {Enter Up}
  
#UseHook, Off

~Esc::    
~Tab::
 fSoundPlay := true
 if (vRSh)
   {
    gosub lMainTHQoff2
        vRShX         := false
        vRSh          :=0
     }
return

+ Блок прямого указания стрелок
;--------------------------------------------------------------------------
;Handling routines the main operation keys - gas, brake, and turns (left and right).

;********** Begin section **********

lUp:
    fUDLR := true
    Send, {Up Down}
   vBoostSpeed := 0
     while (GetKeyState("UP", "P"))
    {
      fKeyUpTimer:=true
      sleep %td20_Sleep%
        fnGearSpdBrk(cNoneParam, cFnSB_GT)
      if (fnGearSpdBrk(cNoneParam, cFnSB_Boost))
                continue
          else
            sleep %td20_Sleep% ; 10 ms
        }
     Send, {Up UP}
   fKeyUpTimer:=false
     fUDLR:=false
return

lDown:
    fUDLR:=true
  Send, {Down Down}
   vSharpBrake := 0
     while (GetKeyState("Down", "P"))
    {
      fKeyDnTimer:=true
      sleep %td20_Sleep%
      fnGearSpdBrk(cNoneParam, cFnSB_GT)
      if (fnGearSpdBrk(cNoneParam, cFnSB_Sharp))
                continue
           else
            sleep %td20_Sleep% ; 50 ms               
        }    
    Send, {Down Up}
  fKeyDnTimer:=false  
    fUDLR:=false
return

lLeft:
    ;fUDLR:=true
  Send, {Left Down}
    fnTurnLR(vGearSpdTimer, 5, 1, "Left")
  Send, {Left Up}
    ;fUDLR:=false    
return

lRight:
    ;fUDLR:=true
  Send, {Right Down}
    fnTurnLR(vGearSpdTimer, 5, 1, "Right")
  Send, {Right Up}
    ;fUDLR:=false
return

Всё остальное параметризовано, и легко меняется. Колёсико мыши используется т.к. масштабирование и скролл не работает в машине.

3. Скрипт использует большое число таймеров, которые могут сами запускать другие таймеры, но при минимизации игры, остаётся только дежурный таймер, который снижает общую нагрузку.

4. Звуки к скрипту не прилагаются

5. Конфликты с игрой устранены, кодировка исходника на UTF-8, версия AHK - 1.1.15.01, OS Win7 SP1 x64 Ult.

6. При переделке скрипта на другие игры, я не гарантирую его работоспособность.

7. Если что то не понятно или работает не так как вам хочется - спрашивайте тут.

P.S.  Комментариев много - разобраться не составит проблемы.

Аттач в сл. посте.

"На каждое действие есть равная ему противодействующая критика." Постулат Харриссона
OS Windows 7 x64
AutoHotkey v1.1.32.00 - November 24, 2019
Click to Download

2

Re: AHK: Saints Row The Third (готовый скрипт)

И так, я внёс нужные корректировки.

Вот фрагмент определяющий клавиши, правда стрелки я не стал менять, но их тоже можно поправить по такоможу принципу.

;-----Инициализация
; Скрипт не выгружается
#Persistent
; Запрет повторного запуска
#SingleInstance

cSoundPath := "e:\Sound Forge\THQ\"
fNumLock := false
vNumLock := false
fLockRShift := false 
vDebugTHQ := false ;(true/false)  ;If debugging is enabled, then output your data to control the correct operation (scope of - all script).

;The keys program control, that can be modified.
keyRShift := "F11"
keyPgUp   := "PgUp"
keyPgDn   := "PgDn"
keyEnd    := "End"
keyHome   := "Home"
keyRCtrl  := "F12"

gosub lVarGameTHQ
Return

В аттаче:
1. Откомпилированный EXE (x64)
2. Звуки, которые должны располагаться в e:\Sound Forge\THQ\ (уровень звука не зависит от игры, надо просто его настроить через Микшер громкости)
3. Иконка игры
4. Сам исходник (скрипт немного сложный, так что его правка будет тоже сложной).

Post's attachments

THQ_AHK.rar 1.57 mb, 3 downloads since 2014-07-07 

You don't have the permssions to download the attachments of this post.
"На каждое действие есть равная ему противодействующая критика." Постулат Харриссона
OS Windows 7 x64
AutoHotkey v1.1.32.00 - November 24, 2019
Click to Download

3

Re: AHK: Saints Row The Third (готовый скрипт)

Дополнения - правки

1. В подпрограмме lMainTHQoff2 допущена ошибка, вот правильный вариант

lMainTHQoff2:
  gosub lSetTimerOff
;When you turn off enough to indicate Cycled key, but clearer and less chance go wrong.
         Hotkey, WheelUp,                   lGearInc,              Off
         Hotkey, WheelDown,                 lGearDec,            Off
       Hotkey, Up,                           lUp,                         Off
       Hotkey, Down,                          lDown,                     Off
     Hotkey, Left,                            lLeft,                     Off
     Hotkey, Right,                        lRight,                 Off
         Hotkey, %keyPgUp%,           lMaxGear,         Off         
     Hotkey, %keyPgDn%,           lMinGear,           Off         
       Hotkey, %keyEnd%,            lToggleGearBox,    Off
       Hotkey, %keyHome%,           lCorrectorYaw,    Off    
       Hotkey, %keyRCtrl%,          lSwitchEngine,    Off
     
if (!fSoundPlay)
         {    
          fnPlaySoundTHQ(iSoundStop)
            fSoundPlay := true
         }
return

2. У кого проблемы с разгоном торможением, то фрагмент подпрограммы lVarGameTHQ

;An array of speeds, the higher the value the longer the key is held "Up", "Down", "Left" and "Right".
;The last element of the array is the value of the timer that you want to calculate the constants of the script. 
  arGear   := [1, 25,  75, 125, 175, 250, 600, 600]
 ;An array increment rate and is used to shift the algorithm is simple - arGear[iGear]/arGearIn[iGear]?12
  arGearIn := [1,  1,   2,   2,   3,   4,   5,   5]
 
 gosub lChkArrDef ;The variable/constant cMaxGear defined and tested in routine lChkArrDef.
 cMaxGear--
 iGear      := 1
 iGearTrc := iGear 
 vGearSpd :=  arGear[1]
 vGearBrk :=  arGear[1] 
 
;The minimum value of the timer in the arGear[cMaxGear]=500
 cTimerMin := 100

;Optimum value for cTimerSpd between 105 and 125 milliseconds (with a default period of 250). 
 cTimerSpd := Round(arGear[cMaxGear]/5) 
 
;Multiplier-factor to calculate the remaining constants, do not use integer division "//", and use the standard "/" !
 cTimerFactor := Round(cTimerMin/cTimerSpd,2)  

;Calculation of constant values for timers braking and rotation correction.
 cTimerBrk := Round(cTimerSpd*cTimerFactor*25) 
 ;cTimerSlew := Round(cTimerSpd*cTimerFactor*5)

замените на

;An array of speeds, the higher the value the longer the key is held "Up", "Down", "Left" and "Right".
;The last element of the array is the value of the timer that you want to calculate the constants of the script. 
  arGear   := [1,   30,   90, 150,  200, 300,  400, 625, 625]
 ;An array increment rate and is used to shift the algorithm is simple - arGear[iGear]/arGearIn[iGear]?12
  arGearIn := [1,    2,    2,   2,    3,   3,    4,   5,   5] 

 gosub lChkArrDef ;The variable/constant cMaxGear defined and tested in routine lChkArrDef.
 cMaxGear--
 iGear      := 1
 iGearTrc := iGear 
 vGearSpd :=  arGear[1]
 vGearBrk :=  arGear[1] 
 
;The minimum value of the timer in the arGear[cMaxGear]=500
 cTimerMin := 100

;Optimum value for cTimerSpd between 105 and 125 milliseconds (with a default period of 250). 
 ;cTimerSpd := Round(arGear[cMaxGear]/5) 
cTimerSpd := 135

так будут более плавные повороты и не такой быстрый разгон на низких передачах

"На каждое действие есть равная ему противодействующая критика." Постулат Харриссона
OS Windows 7 x64
AutoHotkey v1.1.32.00 - November 24, 2019
Click to Download

4 (изменено: Indomito, 2014-07-10 09:16:40)

Re: AHK: Saints Row The Third (готовый скрипт)

Да ещё...

1. Подпрограмма lCorrectorYaw используется автоматически при нажатии стрелок/клавиш Left или Right, значит код

Hotkey, %keyHome%,           lCorrectorYaw,    On
и
Hotkey, %keyHome%,           lCorrectorYaw,    Off  

не нужен, т.е. не нужно задействовать клавишу.
Я отказался от корректора поворотов из за его сложности, но компенсатор поворотов всё же есть.

+ Код компенсатора
lLeft:
    ;fUDLR:=true
  Send, {Left Down}
    fnTurnLR(vGearSpdTimer, 5, 1, "Left")
  Send, {Left Up}
    ;fUDLR:=false    
return

lRight:
    ;fUDLR:=true
  Send, {Right Down}
    fnTurnLR(vGearSpdTimer, 5, 1, "Right")
  Send, {Right Up}
    ;fUDLR:=false
return

;The function of soft turn, provides input in the steep turn at high speed.  
fnTurnLR(iTimer, iDec, iInc, iKey)
{
  global ;------

  local vSpdTimer
  local cTimer, cDec, cInc, cKey
  local fReEnter:=false

      if (fReEnter)     ;Protection from of recursion
                return
      fReEnter := true
      cTimer := iTimer, cDec:=iDec, cInc:=iInc, cKey:=iKey
  
      vGearSpdTimer := cTimer
      while (GetKeyState(cKey, "P"))
        {
          vSpdTimer := vGearSpdTimer
          sleep %td50_Sleep%
          while ((GetKeyState(cKey, "P")) && (vGearSpdTimer>0))
            {
              vGearSpdTimer -= cDec
              ;sleep %td50_Sleep%
            }
          while ((GetKeyState(cKey, "P")) && (vGearSpdTimer<vSpdTimer))
            {
              vGearSpdTimer += cInc
              ;sleep %td50_Sleep%
            }      
        }
      fReEnter := false
  return
} 

Сама подпрограмма только выдаёт звук и всё, т.е. нет таймера для обработки(не помню когда отказался)

+ lCorrectorYaw
;Enable/disable the car turn corrections depending on its speed.
lCorrectorYaw:
  if (fScepl)
        return
    if (fCarTurn)                     
      {
             fCarTurn:=false
             fnPlaySoundTHQ(iSoundCorrectorYawOFF)
            }
        else
            {
                fCarTurn:=true
                fnPlaySoundTHQ(iSoundCorrectorYawON)                        
            }                    
return

Но расчёт ведётся, так что осталось написать код в подпрограмме

+ fnGearSpdBrk(vParam0, vSpdBrk)
;---
;Main function to dynamically calculate the speed, braking and turning angle corrector, as well as set the flags for timers speed and braking
;---Beginning of function fnGearSpdBrk
fnGearSpdBrk(vParam0, vSpdBrk) ;The values for vSpdBrk (0 - no matter, 1 - speed of the timer, 2 - braking of the timer, 3 and higher - the other subprogramme)
{
;The constants function fnGearSpdBrk and all the subprogrammes who is calling, they are defined above under subprogramme "lVarGameTHQ".
;cFnSB_Learn||cFnSB_Speed||cFnSB_Brake||cFnSB_GT||cFnSB_Boost||cFnSB_Sharp||cFnSB_Turn||cFnSB_Above||
;          1            2            3         4            5            6           7            8

global ;All variables in the function will be global, it is necessary to comment to engage the directive "global" - should not be an empty string.
local fSpdBrk, vMComp, sLabel, vRetFn, vRetResult
static arSpdBrk := ["lFnSB_Learn","lFnSB_Speed","lFnSB_Brake","lFnSB_GT","lFnSB_Boost","lFnSB_Sharp","lFnSB_Turn","lFnSB_Above"] 
static cErFun := "Error in the function `" fnGearSpdBrk `". `n" 
static fRetDone := 0, fRetErr := -1 
  
  sLabel := arSpdBrk[vSpdBrk]
  if (!IsLabel(sLabel))
   {
         msgbox, % vMsgOptionsEr 
                            ,Saints Row: The Third
              , %cErFun% Dynamic label with name = "%sLabel%" does not exist.`n`n %сErrOfExit%
              ,30
     ExitApp
    }
  ;a  := arSpdBrk[vSpdBrk]
  ;tooltip %a% = %vSpdBrk%
  vRetFn := fRetDone
  gosub, % arSpdBrk[vSpdBrk]
  if (vRetFn = fRetErr)
    {
         sbLabel := SubStr(sLabel, 2)
     msgbox, % vMsgOptionsEr 
                            ,Saints Row: The Third
              , %cErFun% Semantic error in the sub-function = "%sbLabel%" `n`n %сErrOfExit%
              ,30
     ExitApp
    }  

return vRetResult
;----------------------------------------
;-----Остальные обработчики
;----------------------------------------
;The block checks the flags and the initial values for the correction of the rotation.
lFnSB_Turn:
;----------------------------------Тут код для обработчика таймера
  return 
      
rern vRetFn:=fRetErrtu

;----------------------------------------
;-----Остальные обработчики
;----------------------------------------

;While not using - stopgap
; cFnSB_Above := 6
lFnSB_Above: 
return vRetFn:=fRetErr
}
;---End of function fnGearSpdBrk
;---

Далее дополнить

+ Секцию таймеров(там только Up и Dn)
;--------------------------------------------------------------------------
;The three basic routines speed, braking and rotation to them all is based.

;********** Begin section **********

;Subprogramme the timer speed/acceleration.
lMoveUp:
  fnGearSpdBrk(cNoneParam, cFnSB_GT)
  if (fnGearSpdBrk(cNoneParam, cFnSB_Speed))
        return
  if (vGearSpdTimer<=0)
       vGearSpdTimer := 1
  Send, {UP Down}
  sleep %vGearSpdTimer%
  Send, {UP Up}
return

;Subprogramme the timer braking.
lMoveBrk:
  fnGearSpdBrk(cNoneParam, cFnSB_GT)
  if (fnGearSpdBrk(cNoneParam, cFnSB_Brake))
       return
  if (vGearBrkTimer<=0)
       vGearBrkTimer := 1       
  Send, {Down Down}
  sleep %vGearBrkTimer%
  Send, {Down Up}
return

;********** End of section **********
;--------------------------------------------------------------------------

Дополнить секцию ON/OFF таймеров

+ открыть спойлер
;----------Секция ON
lSetTimerOn:
  SetTimer lMoveUp,     %cTimerSpd%
  SetTimer lMoveBrk,    %cTimerBrk%
  ;SetTimer lKeyUpTimer, %сKeyUpTimer%
  ;SetTimer lKeyDnTimer, %cKeyDnTimer%
  return

lMainTHQon1:
    vRSh     :=1
    vRShX         := true
    ;fnGearSpdBrk(false, cFnSB_Turn) ;vSlew      := false
    fUDLR       := false
  fKeyUpTimer := false
  fKeyDnTimer := false  
  vSharpBrake := 0
  vBoostSpeed := 0
  fnGearSpdBrk(cNoneParam, cFnSB_Learn)    
return
;----------Секция OFF
lSetTimerOff:
    SetTimer lMoveUp,     Off
  SetTimer lMoveBrk,    Off
  ;SetTimer lMoveSlew,   Off
  ;SetTimer lKeyUpTimer, Off
  ;SetTimer lKeyDnTimer, Off  
return

lMainTHQoff1:
    vRSh     := 0
    vRShX         := true 
  fScepl      := false
    ;fnGearSpdBrk(false, cFnSB_Turn) ;vSlew      := false
    fUDLR       := false
  fKeyUpTimer := false
  fKeyDnTimer := false  
  vSharpBrake := 0
  vBoostSpeed := 0
    fnGearSpdBrk(cNoneParam, cFnSB_Learn)    
return

2. При старте скрипта передачи стоят "на ручнике", что при старте это поменять достаточно изменить флаг на ИСТИНА fGearBox    := true в подпрограмме lVarGameTHQ

3. Оптимальные значения, просто решил подобрать

  arGear   := [1,   25,   50,   75, 125, 160, 300, 400, 625, 625]
  arGearIn := [1,    1,    2,    2,   3,   2,   4,   4,   5,   5]
  cTimerMin := 100
  cTimerSpd := 127

Вроде всё

"На каждое действие есть равная ему противодействующая критика." Постулат Харриссона
OS Windows 7 x64
AutoHotkey v1.1.32.00 - November 24, 2019
Click to Download