[Python] I have a problem with an AHK v2 script for automating resetting runs in...

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    Ok, so I have been trying to make a program to automate runs in Isaac. I am a beginner in AHK but not in other languages so I thought I'd give it a try with the help of ChatGPT. The thing is that I think it's filled with errors I can't diagnose because I don't know about the functions used.

    To put it simply I want to be able to select a character and then unless some conditions are met the run resets. I'm doing this with OCR (python script works perfectly, ChatGPT helped a bit but I amended it) and the Screenshots with GDI+. This is the code for the ahk v2 script:

    #Include "Gdip_All.ahk" ; Asegúrate de que Gdip_All.ahk está en el mismo directorio o en el directorio Lib de AutoHotkey.

    #SingleInstance Force
    SetTitleMatchMode(2)

    GameTitle := "Binding of Isaac: Afterbirth+"
    GamePath := "D:\SteamLibrary\steamapps\common\The Binding of Isaac Rebirth\isaac-ng.exe"
    PythonPath := "C:\Python312\python.exe" ; Ruta completa al ejecutable de Python
    PythonScriptPath := "C:\Users\arted\OneDrive - unizar.es\Escritorio\AutoHardIsaac\Images.py"
    ScreenshotFilename := "isaac.png"
    ScreenshotDestPath := "C:\Users\arted\OneDrive - unizar.es\Escritorio\AutoHardIsaac\" . ScreenshotFilename
    LogFilePath := "C:\Users\arted\OneDrive - unizar.es\Escritorio\AutoHardIsaac\ahk_log.txt" ; Archivo de log para depuración

    ; Inicializar GDI+
    pToken := Gdip_Startup()
    if !pToken
    {
    MsgBox("Error: No se pudo iniciar GDI+.")
    ExitApp()
    }

    ; Agregar mensaje de inicio de ejecución al archivo de log
    FileAppend("Inicio del script de AutoHotkey.n", LogFilePath)

    ; Mostrar el orden de los personajes en el juego
    MsgBox("Elige un número según el orden de los personajes:n1. Isaacn2. Magdalenen3. Cainn4. Judasn5. ??? (Blue Baby)n6. Even7. Samsonn8. Azazeln9. Lazarusn10. Edenn11. The Lostn12. Lilithn13. Apollyonn14. Aleatorio", "Orden de Personajes", 0)

    ; Preguntar al usuario para seleccionar el personaje
    IB := InputBox("Introduce el número del personaje que deseas usar (del 1 al 14):", "Selección de Personaje", "w300 h150"), Personaje := IB.Value, ErrorLevel := IB.Result="OK" ? 0 : IB.Result="CANCEL" ? 1 : IB.Result="Timeout" ? 2 : "ERROR"
    if ErrorLevel
    {
    MsgBox("Cancelaste la selección de personaje.")
    FileAppend("Usuario canceló la selección de personaje.n", LogFilePath)
    ExitApp()
    }

    ; Convertir la entrada a número
    Personaje := Trim(Personaje)
    FileAppend("Personaje seleccionado: " Personaje "n", LogFilePath)

    ; Abrir el juego si no está ya activo
    if !WinExist(GameTitle)
    {
    Run(GamePath)
    FileAppend("Intentando abrir el juego.n", LogFilePath)
    ErrorLevel := !WinWait(GameTitle, , 10)
    if !WinActive(GameTitle)
    {
    ToolTip("Error: No se pudo abrir el juego.")
    Sleep(5000)
    ToolTip() ; Ocultar el ToolTip
    FileAppend("Error: No se pudo abrir el juego.n", LogFilePath)
    Sleep(3000)
    ExitApp()
    }
    }

    Sleep(7000) ; Espera para que el juego cargue completamente
    FileAppend("Juego cargado.n", LogFilePath)

    if !WinActive(GameTitle)
    {
    WinActivate(GameTitle)
    Sleep(100)
    FileAppend("Juego activado.n", LogFilePath)
    }

    ; Automatizar el proceso de inicio desde los créditos
    Send("{Enter down}")
    Sleep(500)
    Send("{Enter up}")
    Sleep(1500)

    Send("{Enter down}")
    Sleep(500)
    Send("{Enter up}")
    Sleep(1500)

    Send("{Right down}") ; Mover a la derecha para seleccionar el save 2
    Sleep(500)
    Send("{Right up}")
    Sleep(500)

    Send("{Enter down}") ; Selecciona el save 2
    Sleep(500)
    Send("{Enter up}")
    Sleep(1500)

    Send("{Up down}") ; Mover hacia arriba para seleccionar "New Run"
    Sleep(500)
    Send("{Up up}")
    Sleep(500)

    Send("{Enter down}") ; Entra en la selección de personajes
    Sleep(500)
    Send("{Enter up}")
    Sleep(1500)

    ; Seleccionar personaje basado en la entrada del usuario
    Switch Personaje
    {
    Case "1": ; Isaac (default, no movement needed)
    ; No se hace nada, ya que Isaac es el personaje seleccionado por defecto
    Case "2": ; Magdalene
    Send("{Right down}") ; Mover una vez a la derecha
    Sleep(250)
    Send("{Right up}")
    Case "3": ; Cain
    Send("{Right down 2}") ; Mover dos posiciones a la derecha
    Sleep(250)
    Send("{Right up}")
    Case "4": ; Judas
    Send("{Right down 3}")
    Sleep(250)
    Send("{Right up}")
    Case "5": ; ??? (Blue Baby)
    Send("{Right down 4}")
    Sleep(250)
    Send("{Right up}")
    Case "6": ; Eve
    Send("{Right down 5}")
    Sleep(250)
    Send("{Right up}")
    Case "7": ; Samson
    Send("{Right down 6}")
    Sleep(250)
    Send("{Right up}")
    Case "8": ; Azazel
    Send("{Right down 7}")
    Sleep(250)
    Send("{Right up}")
    Case "9": ; Lazarus
    Send("{Right down 8}")
    Sleep(250)
    Send("{Right up}")
    Case "10": ; Eden
    Send("{Right down 9}")
    Sleep(250)
    Send("{Right up}")
    Case "11": ; The Lost
    Send("{Right down 10}")
    Sleep(250)
    Send("{Right up}")
    Case "12": ; Lilith
    MsgBox("Lilith aún no está desbloqueada. Por favor, elige otro personaje.")
    FileAppend("Lilith aún no está desbloqueada. Salida del script.n", LogFilePath)
    ExitApp()
    Case "13": ; Apollyon
    Send("{Right down 12}")
    Sleep(250)
    Send("{Right up}")
    Case "14": ; Aleatorio
    Send("{Right down 13}") ; Seleccionar el personaje aleatorio
    Sleep(250)
    Send("{Right up}")
    Default:
    MsgBox("Personaje no válido. Elige un número entre 1 y 14.")
    FileAppend("Error: Personaje no válido seleccionado.n", LogFilePath)
    ExitApp()
    }

    if !WinActive(GameTitle)
    {
    WinActivate(GameTitle)
    Sleep(100)
    }
    Send("{Enter down}") ; Confirmar selección de personaje y comenzar la run
    Sleep(500)
    Send("{Enter up}")
    Sleep(2500)

    Loop
    {
    ; Asegúrate de que el juego esté activo
    if !WinActive(GameTitle)
    {
    WinActivate(GameTitle)
    Sleep(100)
    }
    Sleep(1200)

    ; Capturar usando DWM Thumbnails
    hwnd := WinGetID(GameTitle)
    DwmRegisterThumbnail(hwnd, 0, hwndThumb)
    DwmQueryThumbnailSourceSize(hwndThumb, Width, Height)

    hbm := Gdip_CreateBitmap(Width, Height)
    hdc := Gdip_GetImageGraphicsContext(hbm)

    ; Copiar el contenido del thumbnail al bitmap
    DwmUpdateThumbnailProperties(hwndThumb, 0, 0, Width, Height, hdc)

    ; Guardar la captura de pantalla usando GDI+
    Gdip_SaveBitmapToFile(hbm, ScreenshotDestPath)

    ; Liberar recursos de la imagen y thumbnail
    Gdip_DeleteGraphics(hdc)
    Gdip_DisposeImage(hbm)
    DwmUnregisterThumbnail(hwndThumb)

    FileAppend("Captura de pantalla guardada en: " ScreenshotDestPath "n", LogFilePath)

    ; Ejecuta el script de Python para verificar las condiciones
    command := PythonPath . " `"" . PythonScriptPath . "`""
    FileAppend("Ejecutando comando: " command "n", LogFilePath)
    RunWait(command, , "Hide", &PythonPID)

    ; Leer el archivo de resultados de Python
    Result := FileRead("C:\Users\arted\OneDrive - unizar.es\Escritorio\AutoHardIsaac\resultado.txt")
    FileAppend("Resultado leído: " Result "n", LogFilePath)

    ; Si se encuentran las condiciones deseadas, pausar el script y esperar reactivación
    if (Result = "True")
    {
    Send("{Esc up}")
    Sleep(100)
    Send("{Esc down}")
    Sleep(100)

    FileAppend("Condiciones encontradas. Script pausado.n", LogFilePath)

    Pause() ; Pausa el script y espera a que presiones F12 para reanudar
    }
    else
    {
    FileAppend("Condiciones no encontradas. Reiniciando run.n", LogFilePath)
    ; Reinicia la run manteniendo la tecla "R" presionada
    Send("{r down}")
    Sleep(1500) ; Mantener "R" presionada por 1.5 segundos
    Send("{r up}")
    }
    }

    ; Tecla para reactivar el script
    F12::pause()

    CerrarGDIplus:
    Gdip_Shutdown(pToken)
    ExitApp()
    Return


    Tell me if you need the python script too or not, thanks!

    I tried telling ChatGPT all the errors but it didn't fix any of them, it only sent me the same version again and again. I also tried searching for some documentation but I haven't been able to find it.

    Continue reading...

Compartilhe esta Página