Update client_server.au3

Update client_server.au3

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Outfile=Client32.exe
#AutoIt3Wrapper_Outfile_x64=Client64.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=y
#AutoIt3Wrapper_Compile_Both=y
#AutoIt3Wrapper_UseX64=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; #SCRIPT# ======================================================================================================================
; Name ..........: client_server.au3
; Author ........: Luigi (Luismar Chechelaky)
; Description ...: controle de botões e slider por POST request, com client/servidor em PHP em HTTPs
;                  control button and slider over POST requst, with client/server em PHP over HTTPs
; Link ..........: https://github.com/chechelaky/AutoIt/tree/master/ClientServer
; start server first, then start client
; ===============================================================================================================================

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <SliderConstants.au3>
#include <GuiRichEdit.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <Timers.au3>
#include <ButtonConstants.au3>
#include <ComboConstants.au3>
#include <Debug.au3>

#include <JSMN.au3> ; https://github.com/chechelaky/AutoIt/blob/master/JSMN.au3
#include <object_dump.au3> ; https://github.com/chechelaky/AutoIt/blob/master/object_dump.au3
#include "base64.au3" ; https://github.com/chechelaky/AutoIt/blob/master/base64-2.au3

OnAutoItExitRegister("OnExit")

Global $xx = 10
Global $WHO = @ScriptName = "client_server.au3" ? "Client" : "Server"

If @Compiled Then $WHO = "Client"
Global $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")
Global $hSliderTic

If $CmdLine[0] Then
	$xx = $CmdLine[1]
ElseIf $WHO = "Client" Then
	Run('"C:\Program Files (x86)\AutoIt3\AutoIt3.exe" "C:\Dropbox\BoriusIOT\server_2.au3" 690')
	If Not FileCopy("C:\Dropbox\BoriusIOT\client_2.au3", "C:\Dropbox\BoriusIOT\server_2.au3", 1) Then Exit
EndIf

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $hGui, $hEdit
Global $TIMER[4] = [0, 0]
Global $DUMMY
Global $WORK
Global $DEBUG = False

Global $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
Global $REMOTE_URL = "https://www.borius.com.br/api/runner.php"
;~ Global $REMOTE_URL = "http://192.168.100.2/borius/run.php"
Global $REMOTE_USER, $REMOTE_PASS, $AUTHORIZATION

Global $oHwd = ObjCreate("Scripting.Dictionary")
Global $oPin = ObjCreate("Scripting.Dictionary")
Global $oVal = ObjCreate("Scripting.Dictionary")
Global $oTag = ObjCreate("Scripting.Dictionary")
Global $oLab = ObjCreate("Scripting.Dictionary")
Global $oSend = ObjCreate("Scripting.Dictionary")
Global $aSend[1], $aNew[1]

$hGui = GUICreate($WHO, 670, 600, $xx, 10, Default, $WS_EX_COMPOSITED)
GUISetFont(9, 400, 0, "DOSLike", $hGui)
GUISetOnEvent($GUI_EVENT_CLOSE, "Quit")
$DUMMY = GUICtrlCreateButton("", 0, 0, 0, 0)
$hEdit = _GUICtrlRichEdit_Create($hGui, "", 340, 10, 320, 580, BitOR($ES_MULTILINE, $WS_VSCROLL, $ES_AUTOVSCROLL, $ES_READONLY))

Switch $WHO
	Case "Client"
		$REMOTE_USER = "IuNQTOFeBr1H8F4eMckWbfqtoDfCXAfen3mTBhg"
		$REMOTE_PASS = "mLePz9eTJ1IYN8uuuF3l2Ny3x3fTI09kdHXPCQ"
		$AUTHORIZATION = "Basic " & B64Encode($REMOTE_USER & ":" & $REMOTE_PASS)
	Case "Server"
		$REMOTE_USER = "Pm4DAWpv5Q2wZ4JW3qfPDNPxJP760dZTU7ysnsJ"
		$REMOTE_PASS = "Grwv5agziFgsEycmHrOYjhR7oIa4bPDVSscUp3"
		$AUTHORIZATION = "Basic " & B64Encode($REMOTE_USER & ":" & $REMOTE_PASS)
		$DEBUG = True
		If $DEBUG Then _DebugSetup($WHO, True, 4, $WHO & ".log", True)
EndSwitch
;~ ConsoleWrite("$REMOTE_USER[ " & $REMOTE_USER & " ]" & @LF)
;~ ConsoleWrite("$REMOTE_PASS[ " & $REMOTE_PASS & " ]" & @LF)
;~ ConsoleWrite("$REMOTE_USER:$REMOTE_PASS[ " & $REMOTE_USER & ":" & $REMOTE_PASS & " ]" & @LF)
;~ ConsoleWrite("_Base64Encode[ " & B64Encode($REMOTE_USER & ":" & $REMOTE_PASS) & " ]" & @LF)
;~ ConsoleWrite("$AUTHORIZATION[ " & $AUTHORIZATION & " ]" & @LF)
;~ $hSliderTic = GUICtrlCreateSlider(290, 124, 40, 160, $TBS_VERT, $WS_EX_COMPOSITED)
;~ Analogic(7, 250, 110)

Func Block()
	For $each In $oHwd
		GUICtrlSetState($each, $GUI_DISABLE)
		GUICtrlSetBkColor($each, 0xF0F0F0)
		If StringLower(StringMid($oHwd.Item($each), 1, 1)) = "a" Then
			GUICtrlSetData($each, 1023)
			GUICtrlSetData($oTag.Item($each), 0)
			GUICtrlSetColor($oLab.Item($each), 0x6D6D6D)
			GUICtrlSetColor($oTag.Item($each), 0x6D6D6D)
		EndIf
	Next
	GUICtrlSetState($DUMMY, $GUI_FOCUS)
EndFunc   ;==>Block

Func UnBlock()
	For $each In $oHwd
		GUICtrlSetState($each, $GUI_ENABLE)
		If StringLower(StringMid($oHwd.Item($each), 1, 1)) = "a" Then
			GUICtrlSetColor($oLab.Item($each), 0x000000)
			GUICtrlSetColor($oTag.Item($each), 0x000000)
		EndIf
	Next
EndFunc   ;==>UnBlock

Func Digital($pin, $xx, $yy)
	Local $handle = GUICtrlCreateButton($pin, $xx, $yy, 40, 20)
	GUICtrlSetOnEvent($handle, "DigitalSet")
	$oHwd.Add($handle, $pin)
	$oPin.Add($pin, $handle)
	$oVal.Add($pin, 0)
	GUICtrlSetBkColor($handle, 0xFF0000)
EndFunc   ;==>Digital

Func Analogic($pin, $xx, $yy)
	Local $handle = GUICtrlCreateSlider($xx, $yy + 14, 40, 160, $TBS_VERT, $WS_EX_COMPOSITED)
	Local $label = GUICtrlCreateLabel($pin, $xx, $yy, 40, 15)
	Local $tag = GUICtrlCreateLabel(0, $xx, $yy + 172, 36, 15, $SS_CENTER, $WS_EX_TOPMOST)
	GUICtrlSetLimit($handle, 1023, 0)
	GUICtrlSetOnEvent($handle, "AnalogicSet")
	$oHwd.Add($handle, $pin)
	$oPin.Add($pin, $handle)
	$oVal.Add($pin, 0)
	GUICtrlSetData($handle, 1023)
	$oLab.Add($handle, $label)
	$oTag.Add($handle, $tag)
EndFunc   ;==>Analogic

Func DigitalSet($pin = 0, $val = 0)
	If IsDeclared("pin") And IsDeclared("val") Then
		Local $hwd = $oPin.Item($pin)
		$oVal.Item($pin) = Number($val) ? 1 : 0
		GUICtrlSetBkColor($hwd, $val ? 0x00FF00 : 0xFF0000)
		GUICtrlSetState($hwd, $GUI_ENABLE)
	Else
		Assign("pin", $oHwd.Item(@GUI_CtrlId))
		If Number($oVal.Item($pin)) Then
			GUICtrlSetBkColor(@GUI_CtrlId, 0xFF0000)
			$oVal.Item($pin) = 0
		Else
			GUICtrlSetBkColor(@GUI_CtrlId, 0x00FF00)
			$oVal.Item($pin) = 1
		EndIf
		If Not $oSend.Exists($pin) Then
			$oSend.Add($pin, $oVal.Item($pin))
		Else
			$oSend.Item($pin) = $oVal.Item($pin)
		EndIf
		GUICtrlSetState($DUMMY, $GUI_FOCUS)
	EndIf
EndFunc   ;==>DigitalSet

Func AnalogicSet($pin = 0, $val = 0)
	If IsDeclared("pin") And IsDeclared("val") Then
		Local $hwd = $oPin.Item($pin)
		$oVal.Item($pin) = 1023 - Limit($val)
		GUICtrlSetData($hwd, $oVal.Item($pin))
		GUICtrlSetData($hwd, $oVal.Item($pin))
		GUICtrlSetData($oTag.Item($hwd), 1023 - $oVal.Item($pin))
		GUICtrlSetState($hwd, $GUI_ENABLE)
	Else
		Assign("pin", $oHwd.Item(@GUI_CtrlId))
		$pin = $oHwd.Item(@GUI_CtrlId)
		$oVal.Item($pin) = 1023 - GUICtrlRead(@GUI_CtrlId)
		GUICtrlSetData($oTag.Item(@GUI_CtrlId), $oVal.Item($pin))
		If Not $oSend.Exists($pin) Then
			$oSend.Add($pin, $oVal.Item($pin))
		Else
			$oSend.Item($pin) = $oVal.Item($pin)
		EndIf
;~ 		GUICtrlSetState(@GUI_CtrlId, $GUI_DISABLE)
;~ 		GUICtrlSetState($DUMMY, $GUI_FOCUS)
	EndIf
EndFunc   ;==>AnalogicSet

Func VectorSet($pin, $val)
EndFunc   ;==>VectorSet

Func FloatSet($pin, $val)
EndFunc   ;==>FloatSet

Func Limit($ii, $nn = 0, $xx = 1023)
	Return $ii < $nn ? $nn : $ii > $xx ? $xx : $ii
EndFunc   ;==>Limit

#Region
Work($WORK)
Digital("d22", 10, 40)
Digital("d23", 50, 40)
Digital("d24", 90, 40)
Digital("d25", 130, 40)
Digital("d26", 170, 40)
Digital("d27", 210, 40)
Digital("d28", 250, 40)
Digital("d29", 10, 60)
;~ Digital("d9", 50, 60)
;~ Digital("d10", 90, 60)
;~ Digital("d11", 130, 60)
;~ Digital("d12", 170, 60)
;~ Digital("d13", 210, 60)
;~ Digital("d14", 250, 60)

;~ Digital("d15", 10, 80)
;~ Digital("d16", 50, 80)
;~ Digital("d17", 90, 80)
;~ Digital("d18", 130, 80)
;~ Digital("d19", 170, 80)
;~ Digital("d20", 210, 80)
;~ Digital("d21", 250, 80)

Analogic("a1", 10, 110)
Analogic("a2", 50, 110)
Analogic("a3", 90, 110)
Analogic("a4", 130, 110)
Analogic("a5", 170, 110)
Analogic("a6", 210, 110)
Analogic("a7", 250, 110)
;~ Analogic("tic", 290, 110)
#EndRegion

GUISetState(@SW_SHOW, $hGui)
Block()

While Sleep(25)
	WorkRun()
WEnd

Func OnExit()
	If $WORK[0] = 2 Or $WORK[0] = 3 Then Ajax($WHO & "Off")
	GUISetState($hGui, @SW_HIDE)
	GUIDelete($hGui)
	$oHTTP = 0
EndFunc   ;==>OnExit

Func Quit()
	Exit
EndFunc   ;==>Quit

Func Work(ByRef $WORK, $xx = 10, $yy = 10, $ww = 160, $hh = 25)
	Local $arr[4] = [0]
	$arr[1] = GUICtrlCreateButton("", $xx, $yy, $ww, $hh)
	$arr[2] = GUICtrlCreateProgress($xx + 3, $yy - 8, $ww - 6, 8)
	$arr[3] = GUICtrlCreateLabel("0", $ww + $xx + 13, $yy + 3, 80, 20, $SS_CENTER)
	GUICtrlSetOnEvent($arr[1], "WorkTry")
	$WORK = $arr
	WorkSet(0)
EndFunc   ;==>Work

Func WorkTry()
	Switch $WORK[0]
		Case 0
			Ajax($WHO & "On")
		Case 2
			Ajax($WHO & "Off")
		Case 3, 4
			WorkSet(0)
	EndSwitch
EndFunc   ;==>WorkTry

Func WorkSet($mode = 0, $iTime = 0, $err = 0)
	$WORK[0] = Number($mode)
	$TIMER[1] = $iTime
	GUICtrlSetData($WORK[3], "[ " & $TIMER[1] & " ]")
	Switch $WORK[0]
		Case 0
			GUICtrlSetBkColor($WORK[1], 0xF0F0F0)
			GUICtrlSetData($WORK[1], "OFF")
			Block()
		Case 2
			GUICtrlSetBkColor($WORK[1], 0xCCFFCC)
			GUICtrlSetData($WORK[1], "ON")
			UnBlock()
		Case 3
			GUICtrlSetBkColor($WORK[1], 0xFFCC99)
			GUICtrlSetData($WORK[1], "OFF LINE")
			$TIMER[3] = 0
			Block()
		Case 4
			GUICtrlSetBkColor($WORK[1], 0xFFCC99)
			GUICtrlSetData($WORK[1], "ERROR")
			$TIMER[3] = 0
			Block()
	EndSwitch
EndFunc   ;==>WorkSet

Func WorkRun()
	If $TIMER[1] Then
		If TimerDiff($TIMER[0]) >= ($TIMER[1] + $TIMER[3]) Then
			$TIMER[0] = _Timer_Init()
			Ajax($WHO & ($WORK[0] = 2 ? "Get" : "On"))
		EndIf
		GUICtrlSetData($WORK[3], "[ " & $TIMER[1] + $TIMER[3] & " ]")
		GUICtrlSetData($WORK[2], Int((TimerDiff($TIMER[0]) / ($TIMER[1] + $TIMER[3])) * 100))
	Else
		GUICtrlSetData($WORK[2], 0)
		$TIMER[0] = 0
		$TIMER[3] = 0
	EndIf

EndFunc   ;==>WorkRun

Func Ajax($func = "")
	$oHTTP.Open("POST", $REMOTE_URL, False)
	$oHTTP.SetRequestHeader("User-Agent", "AutoIt")
	$oHTTP.SetRequestHeader("Content-Type", "application/json; charset=utf-8")
	$oHTTP.SetRequestHeader("Connection", "Keep-Alive")
	$oHTTP.SetRequestHeader("Authorization", $AUTHORIZATION)
;~ 	$oHTTP.SetCredentials($REMOTE_USER, $REMOTE_PASS, 1)
;~ 	Local $opt = '{"Pergunta":"' & $func & '"' & ($data ? ',"d":' & $data : "") & '}'
	Local $opt = ObjCreate($SD)
	$opt.Add("Pergunta", $func)
	If $oSend.Count Then
		$opt.Add("data", $oSend)
		$oSend = ObjCreate($SD)
	EndIf
	$opt = jsmn_encode($opt)
	Console(">> " & $opt)
	$oHTTP.Send(StringToBinary($opt, 4))

	$oHTTP.WaitForResponse()
	Local $oAllHeaders = $oHTTP.GetAllResponseHeaders()
	ConsoleWrite($oAllHeaders & @LF)
	If $oHTTP.Status <> 200 Then Return WorkSet(4, 0, 1)

	Local $oo = $oHTTP.ResponseText
	If Not $oo Then Return WorkSet(4, 0, 2)
	If $DEBUG Then _DebugOut($oo)
	Console($oo)
	$oo = Jsmn_decode($oo)
	If @error Then Return WorkSet(4, 0, 3)
	WorkReturn($oo, $oHTTP.ResponseText)
EndFunc   ;==>Ajax

Func HeartBeat($hs = 0)
	If $TIMER[1] Then
		$TIMER[3] = 1000 - $hs
		If $TIMER[3] > 500 Then $TIMER[3] = 500
	Else
		$TIMER[3] = 0
	EndIf
EndFunc   ;==>HeartBeat

Func WorkReturn($oo = 0, $txt = "")
	Switch $WHO
		Case "Client"
			If Not $oo.Exists("work") Then Return WorkSet(4, 6000, 4)
			If Not $oo.Item("work") Then Return WorkSet(3, 6000, 5)
		Case "Server"
	EndSwitch

	If $oo.Exists("Resposta") Then
		Console('<< {"Resposta":"' & $oo.Item("Resposta") & '"}')
		Switch $oo.Item("Resposta")
			Case "ServerOn"
				WorkSet(2, 2000)
				If $oo.Exists("news") Then
					Set($oo.Item("news"))
					UnBlock()
				EndIf
			Case "ServerOff"
				WorkSet(0, 0)
				Block()
			Case "ServerGet"
				If $oo.Exists("news") Then Set($oo.Item("news"))
				WorkSet(2, 2000)
			Case "ClientOn"
				WorkSet(2, 2000)
				If $oo.Exists("news") Then
					Set($oo.Item("news"))
					UnBlock()
				EndIf
			Case "ClientOff"
				WorkSet(0, 0)
				Block()
			Case "ClientGet"
				If $oo.Exists("news") Then Set($oo.Item("news"))
				If $oo.Exists("b") Then HeartBeat($oo.Item("b"))
				WorkSet(2, 2000)
		EndSwitch
	Else

	EndIf
EndFunc   ;==>WorkReturn

Func Set($pin = 0, $val = 0)
	If IsObj($pin) Then
		For $each In $pin
			Set($each, $pin.Item($each))
		Next
	Else
;~ 		Console("pin[" & $pin & "] val[" & $val & "] <" & StringMid($pin, 1, 1) & ">")
		Switch StringLower(StringMid($pin, 1, 1))
			Case "d"
				DigitalSet($pin, $val)
			Case "a"
				AnalogicSet($pin, $val)
			Case "v"
				VectorSet($pin, $val)
			Case "f"
				FloatSet($pin, $val)
		EndSwitch
	EndIf
EndFunc   ;==>Set

Func Console($sInput, $hour = 0, $sAttrib = "", $iColor = "")
	;	http://www.autoitscript.com/forum/topic/121728-richedit-not-working/
	Local $Comprimento = StringLen($sInput), $PASSO = 59, $Temp = ""
	;	Count the @CRLFs
	StringReplace(_GUICtrlRichEdit_GetText($hEdit, True), @CRLF, "")
	Local $iLines = @extended
	;	Adjust the text char count to account for the @CRLFs
	Local $iEndPoint = _GUICtrlRichEdit_GetTextLength($hEdit, True, True) - $iLines
	;	Add new text
	;_GUICtrlRichEdit_AppendText($hEdit, $sInput & @CRLF)
	If $Comprimento > $PASSO Then
		For $ii = 1 To $Comprimento Step $PASSO
			If $hour Then
				$Temp &= $ii = 1 ? (@HOUR & ":" & @MIN & ":" & @SEC & " ") : "         "
				$Temp &= StringMid($sInput, $ii, $PASSO) & @CRLF
			Else
				$Temp &= StringMid($sInput, $ii, $PASSO) & @CRLF
			EndIf

		Next
		_GUICtrlRichEdit_AppendText($hEdit, $Temp & StringMid($sInput, $ii, $PASSO))
	Else
		_GUICtrlRichEdit_AppendText($hEdit, $hour ? (@HOUR & ":" & @MIN & ":" & @SEC & " ") : "" & $sInput & @CRLF)
	EndIf
	;	Select text between old and new end points
	_GUICtrlRichEdit_SetSel($hEdit, $iEndPoint, -1)
	;	Convert colour from RGB to BGR
	If $iColor Then
		$iColor = Hex($iColor, 6)
		$iColor = "0x" & StringMid($iColor, 5, 2) & StringMid($iColor, 3, 2) & StringMid($iColor, 1, 2)
		_GUICtrlRichEdit_SetCharColor($hEdit, $iColor ? $iColor : 0x000000)
	Else
		_GUICtrlRichEdit_SetCharColor($hEdit, 0x000000)
	EndIf
	;	Set size
	If $sAttrib Then _GUICtrlRichEdit_SetCharAttributes($hEdit, $sAttrib)
	_GUICtrlRichEdit_SetFont($hEdit, 6, "DOSLike")
	;	Clear selection
	_GUICtrlRichEdit_Deselect($hEdit)
EndFunc   ;==>Console

Func _ErrFunc($oError)
	Local $HexNumber
	Local $strMsg

	$HexNumber = String(Hex($oError.Number, 8))
	$strMsg = "Error Number: " & $HexNumber & @CRLF
	$strMsg &= "WinDescription: " & $oError.WinDescription & @CRLF
	$strMsg &= "Script Line: " & $oError.ScriptLine & @CRLF
;~ 	MsgBox(0, "ERROR", $strMsg)
	SetError(1, $oError.ScriptLine, $HexNumber)

;~ 	; Do anything here.
;~ 	ConsoleWrite("err.number is: " & @TAB & $oError.number & @CRLF & _
;~ 			"err.windescription:" & @TAB & $oError.windescription & @CRLF & _
;~ 			"err.description is: " & @TAB & $oError.description & @CRLF & _
;~ 			"err.source is: " & @TAB & $oError.source & @CRLF & _
;~ 			"err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _
;~ 			"err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _
;~ 			"err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _
;~ 			"err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _
;~ 			"err.retcode is: " & @TAB & $oError.retcode & @CRLF & @CRLF)
EndFunc   ;==>_ErrFunc


OBS Script AmarecTV No Frame Windows Support

;
;  IkaLog
;  ======
;  Copyright (C) 2015 Takeshi HASEGAWA
;
;  Licensed under the Apache License, Version 2.0 (the 'License');
;  you may not use this file except in compliance with the License.
;  You may obtain a copy of the License at
;
;      http://www.apache.org/licenses/LICENSE-2.0
;
;  Unless required by applicable law or agreed to in writing, software
;  distributed under the License is distributed on an 'AS IS' BASIS,
;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;  See the License for the specific language governing permissions and
;  limitations under the License.

;
;  Start and stop recording using Open Broadcaster Software(OBS).
;
;  To Start Recording:
;    ControlAmarecTV.au3 start
;
;  To Stop Recording:
;    ControlAmarecTV.au3 stop
;
;  To Reanem the recording:
;    If you want to rename the recording to a specific filename,
;    Specifcy the filename as environment variables
;    IKALOG_MP4_DESTDIR and IKALOG_MP4_DESTNAME.
;
;  Though this script will sleep seconds so that work on
;  a specific environment. The behavior is subject to change.
;

#include <FileConstants.au3>
#include <StringConstants.au3>

;ƍD݂ɍ킹Ēlݒ肵ĂB
;SendL[̒l̏ɂ  https://www.autoitscript.com/autoit3/docs/appendix/SendKeys.htm
Const $SendKeyValue = "^z"		;AmaRecTV̘^Jnɐݒ肳ĂL[̒l
Const $STARTsleepSec = 0		;^Jn̑ҋ@ԁibŎwj
Const $STOPsleepSec = 10			;^Ȋҋ@ԁibŎwj
Const $RENAMEsleepSec = 3		;^Iナl[܂ł̑ҋ@ԁibŎwj

Func RenameFile($source)
   Local $dest = EnvGet('IKALOG_MP4_DESTNAME')
   $dest = StringReplace($dest, "/", "\")
   If $dest = '' Then
		Return False
   EndIf

   ; IkaLog assumes mp4 as video file extension, but AmarecTV uses avi.
   If StringRight($dest, 4) = ".mp4" Then
	  $dest = StringReplace($dest, ".mp4", ".avi", -1)
   EndIf

   FileMove($source, $dest, $FC_OVERWRITE)
EndFunc

Func FindRecentRecording()
   Local $directory = EnvGet('IKALOG_MP4_DESTDIR')

   ; Replace all slashes to backslashes.
   ; $directory also needs a backslash at its end.
   $directory = StringReplace($directory, "/", "\")
   If StringRight($directory, 1) <> "\" Then
	  $directory = $directory & "\"
   EndIf

   Local $hSearch = FileFindFirstFile($directory & "*.avi*")

   If $hSearch = -1 Then
	  MsgBox(0, "Error", "Could not find any candinates in " & $directory & " (path 1)", 10)
	  Return False
   EndIf

   Local $latest_file = ''
   Local $latest_timestamp = ''

   While True
	  Local $file = FileFindNextFile($hSearch)
	  If @error Then ExitLoop

	  Local $timestamp = FileGetTime($directory & $file, $FT_MODIFIED, $FT_STRING)
	  If StringCompare($timestamp, $latest_timestamp) > 0 Then
		 $latest_file = $directory & $file
		 $latest_timestamp = $timestamp
	  EndIf
   WEnd

   FileClose($hSearch)

   If $latest_file = '' Then
	  MsgBox(0, "Error", "Could not find any candinates in " & $directory & " (path 2)", 10)
	  Return False
   EndIf

   Return $latest_file
EndFunc

Func ControlAmarecTV($stop)
   Local $hWnd = WinWait('[CLASS:AmaRecTV; INSTANCE:2]', '', 1)

   If $hWnd = 0 Then
	  MsgBox(0, "Error", "Could not find AmarecTV")
	  Return False
   EndIf

   Local $text = ControlGetText($hWnd, "", "[CLASS:msctls_statusbar32]")
   Local $inRecording = StringInStr($text, '^撆...') > 0

   ;Xg擾nhƔr,ႤƂ̓t[ȂƂ݂Ȃւ
   Local $ListhWnd = GetAmaRecHandleFromList()
   If ($ListhWnd <> 0) And ($ListhWnd <> $hWnd) Then
	  $hWnd = $ListhWnd
   EndIf

   Local $click = False
   If $inRecording and $stop Then
	  ;Stop Recording.
	  $click = True
   ElseIf (Not $inRecording) and (Not $stop) Then
	  ; Start Recording.
	  $click = True
   EndIf

   If $click Then
	  If $stop Then
		 ; ^Iҋ@
		 Sleep(1000 * $STOPsleepSec)
	  Else
		 ; ^Jnҋ@
		 Sleep(1000 * $STARTsleepSec)
	  EndIf

	  WinActivate($hWnd)
	  WinWaitActive($hWnd, "", 1)

	  ; SendKey
	  Send($SendkeyValue)

	  If $stop Then
		 If EnvGet('IKALOG_MP4_DESTDIR') <> "" Then
			Sleep(1000 * $RENAMEsleepSec)
			Local $file  = FindRecentRecording()
			RenameFile($file)
		 EndIf
	  EndIf
   EndIf

EndFunc

;EChEA^CgAmaRecTV, NXDisplay܂܂ĂAAmaRecTVƔFănhԂ
Func IsVisible($handle)
   If BitAnd( WinGetState($handle), 2 ) Then
	  Return 1
   Else
	  Return 0
   EndIf
EndFunc
; $var[$i][0]:^Cg, $var[$i][1]:nh
Func GetAmaRecHandleFromList()
   Local $var = WinList()
   Local $retValue = 0
   For $i = 1 to $var[0][0]
	  ; ŖÔEBhÊ
	  If $var[$i][0] <> "" AND IsVisible($var[$i][1]) Then	;̔Oƌ듮삵܂
		 If StringInStr($var[$i][0], "AmaRecTV") Then
			If (StringInStr(WinGetClassList($var[$i][0]), "Display")) Then
			   $retValue = $var[$i][1]
			   Return $retValue
			EndIf
		 EndIf
	  EndIf
   Next
   Return $retValue
EndFunc

if ($CmdLine[0] = 0) Then	;exeɃRo[g mFɕ֗Ȃƍlǉ
   Local $msg = StringFormat("%s%s",     "--- NIvV---", @LF)
   $msg = StringFormat("%s%s%s%s%s",$msg, "^Jn:", @ScriptName, " start", @LF)
   $msg = StringFormat("%s%s%s%s", $msg, "^I:", @ScriptName, " stop" & @LF & @LF)
   $msg = StringFormat("%s%s%s",    $msg, "--- ݂̐ݒ --- ", @LF)
   $msg = StringFormat("%s%s%s%s", $msg, "zbgL[̒l: ", $SendKeyValue, @LF)
   $msg = StringFormat("%s^Jn̑ҋ@ %sb%s", $msg, $STARTsleepSec, @LF)
   $msg = StringFormat("%s^Ȋҋ@ %sb%s", $msg, $STOPsleepSec,  @LF)
   $msg = StringFormat("%sl[̑ҋ@ %sb%s", $msg, $RENAMEsleepSec, @LF)
   MsgBox(64, "NIvV & ݂̐ݒ", $msg)

Else
   $stop = StringCompare($CmdLine[1], 'stop') == 0
   ControlAmarecTV($stop)
EndIf

;
;  IkaLog
;  ======
;  Copyright (C) 2015 Takeshi HASEGAWA
;
;  Licensed under the Apache License, Version 2.0 (the 'License');
;  you may not use this file except in compliance with the License.
;  You may obtain a copy of the License at
;
;      http://www.apache.org/licenses/LICENSE-2.0
;
;  Unless required by applicable law or agreed to in writing, software
;  distributed under the License is distributed on an 'AS IS' BASIS,
;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;  See the License for the specific language governing permissions and
;  limitations under the License.

;
;  Start and stop recording using Open Broadcaster Software(OBS).
;
;  To Start Recording:
;    ControlAmarecTV.au3 start
;
;  To Stop Recording:
;    ControlAmarecTV.au3 stop
;
;  To Reanem the recording:
;    If you want to rename the recording to a specific filename,
;    Specifcy the filename as environment variables
;    IKALOG_MP4_DESTDIR and IKALOG_MP4_DESTNAME.
;
;  Though this script will sleep seconds so that work on
;  a specific environment. The behavior is subject to change.
;

#include <FileConstants.au3>
#include <StringConstants.au3>

Func RenameFile($source)
	Local $dest = EnvGet('IKALOG_MP4_DESTNAME')
	$dest = StringReplace($dest, "/", "\")
	If $dest = '' Then
		Return False
	EndIf

	; IkaLog assumes mp4 as video file extension, but AmarecTV uses avi.
	If StringRight($dest, 4) = ".mp4" Then
		$dest = StringReplace($dest, ".mp4", ".avi", -1)
	EndIf

	FileMove($source, $dest, $FC_OVERWRITE)
EndFunc

Func FindRecentRecording()
	Local $directory = EnvGet('IKALOG_MP4_DESTDIR')

	; Replace all slashes to backslashes.
	; $directory also needs a backslash at its end.
	$directory = StringReplace($directory, "/", "\")
	If StringRight($directory, 1) <> "\" Then
		$directory = $directory & "\"
	EndIf

	Local $hSearch = FileFindFirstFile($directory & "*.avi*")

	If $hSearch = -1 Then
		MsgBox(0, "Error", "Could not find any candinates in " & $directory & " (path 1)", 10)
		Return False
	EndIf

	Local $latest_file = ''
	Local $latest_timestamp = ''

	While True
		Local $file = FileFindNextFile($hSearch)
		If @error Then ExitLoop

		Local $timestamp = FileGetTime($directory & $file, $FT_MODIFIED, $FT_STRING)
		If StringCompare($timestamp, $latest_timestamp) > 0 Then
			$latest_file = $directory & $file
			$latest_timestamp = $timestamp
		EndIf
	WEnd

	FileClose($hSearch)

	If $latest_file = '' Then
		MsgBox(0, "Error", "Could not find any candinates in " & $directory & " (path 2)", 10)
		Return False
	EndIf

	Return $latest_file
EndFunc

Func ControlAmarecTV($stop)
	Local $hWnd = WinWait('[CLASS:AmaRecTV; INSTANCE:2]', '', 1)

	If $hWnd = 0 Then
		MsgBox(0, "Error", "Could not find AmarecTV")
		Return False
	EndIf

	Local $text = ControlGetText($hWnd, "", "[CLASS:msctls_statusbar32]")
	Local $inRecording = StringInStr($text, '^撆...') > 0

	Local $click = False
	If $inRecording and $stop Then
		; Stop Recording.
		$click = True
	ElseIf (Not $inRecording) and (Not $stop) Then
		; Start Recording.
		$click = True
	EndIf

	If $click Then
		If $stop Then
			Sleep(1000 * 20)
		EndIf

		; Send Ctrl-Z

		WinActivate($hWnd)
		WinWaitActive($hWnd, "", 1)

		send("^z")

		If $stop Then
			Sleep(1000 * 10)
			Local $file  = FindRecentRecording()
			RenameFile($file)
		EndIf
	EndIf
EndFunc

$stop = StringCompare($CmdLine[1], 'stop') == 0
ControlAmarecTV($stop)


autoitobjectpath

autoitobjectpath

#Region includes
#include-once
#include <array.au3>
#include <date.au3>
#include <File.au3>
#include "AutoItObject/AutoitObject.au3"
#include "micro.test.au3"
#include "micro.test.suite.au3"
#EndRegion includes

_AutoItObject_Startup()

#Region includes
#include-once
#include <array.au3>
#include <date.au3>
#include <File.au3>
#include "AutoitObject.au3"
#include "micro.test.au3"
#include "micro.test.suite.au3"
#EndRegion includes

_AutoItObject_Startup()


latest working

latest working

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!h", "fightArena")
HotKeySet("+!q", "Duel")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")
HotKeySet("+!i", "showStatus")

Global $status="ngondek"
Global $savepixel = 0
Global $screensave[6]
$screensave[0] = 0
$screensave[1] = 0
$screensave[2] = 0
$screensave[3] = 0
$screensave[4] = 0
$screensave[5] = 0

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
;Flag whether to activate quest hunting mode (do quest if there are energy)
$quest_active = False
$match_number = 0
$replay_instead_of_ngarena = True

Do
   Sleep(1)
Until False

Func showStatus()
   ToolTip(StringFormat("%s", $status),1000,0)
EndFunc

Func idle()
   $status = "idle"
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Elseif ($arena_tier==3) Then
	  $arena_tier = 4
	  MsgBox(0, "arena tier", "arena tier is now alltier(when there is no event)", 2)
   ElseIf ($arena_tier==4) Then
	  $arena_tier = 5
	  MsgBox(0, "arena tier", "arena tier is now 5, the special high lvl arena(catalyst, alpha)", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $status = "start arena"
   $allstop = 0
   $quest_play = False
   Do
	  $match_number = $match_number + 1
	  calibrateWindow()
	  if ($quest_active AND PixelGetColor(171,56)==0x5f5f62) Then ;quest is active, make sure not in fight and we can click menu
		 if (checkEnergyIsFull()) Then
			;to reduce stack memory we quit but set flag
			MsgBox(0, "quest", "i want to hunt ISOs", 2)
			$quest_play = True
			$allstop = 1
		 EndIf
	  EndIf
	  ToolTip(StringFormat("match number : %d",$match_number),1000,100)
	  if (Mod($match_number, 5)==0 AND PixelGetColor(171,56)==0x5f5f62) Then
		 MouseClick("left", 138, 58) ;menu
		 Sleep(1000)
		 MouseClick("left", 138, 58) ;menu double
		 Sleep(1000)
		 if (PixelGetColor(400,92)==0x590000) Then
			;send help for the alliance
			MouseClick("left",375,131);alliance
			Sleep(10000)
			MouseClick("left",490,180);help tab
			Sleep(2000)
			Do
			   MouseClick("left",760,235);help button
			   Sleep(2000)
			Until (Not(getDominantColor(PixelGetColor(750,235))=="green"))

			MouseClick("left", 138, 58) ;menu
			Sleep(1000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(1000)
			MouseClick("left", 270, 132) ;fight
			Sleep(8000)
		 EndIf
	  EndIf

	  $arena_continue = 1
	  if ($allstop==0) Then
		 checkInsideFight()
		 Sleep(500)
		 if ($arena_tier==5) Then
			MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			Sleep(500)
			MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			Sleep(500)
		 Else
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			checkInsideFight()
			Sleep(1500)
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
		 EndIf
		 checkInsideFight()
		 Sleep(1000)

		 checkInsideFight()

		 if (Not(getDominantColor(PixelGetColor(346,535))=="green") AND (Not($arena_tier==5))) Then
			MsgBox(0, "fight", "inside fight menu, not arena", 1)
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			Sleep(400)
			MouseClick("left", 500,446)
			Sleep(2000)
			Local $wait = 0
			do
			   Sleep(1000)
			   $wait = $wait+1
			   checkInsideFight()
			Until (getDominantColor(PixelGetColor(435,525))=="green" OR ($wait>10))
		 EndIf
		 checkInsideFight()
		 ;check if currently in one of 3 fights
		 if (PixelGetColor(160,222)==0x2b2c30 AND PixelGetColor(816,222)==0x2b2c30) Then
			Local $leftresult=PixelGetColor(294,280) ;lose 721a1a red, win 26552e
			Local $rightresult=PixelGetColor(697,280)
			if ($leftresult==0x26552e OR $leftresult==0x721a1a) Then
			   if ($rightresult==0x26552e OR $rightresult==0x721a1a) Then
				  MsgBox(0, "fight", "more fight to go", 1)
				  Sleep(1000)
				  MouseClick("left", 200,200)
				  fightArena()
				  $arena_continue = 0
			   EndIf
			EndIf
		 EndIf
		 checkInsideFight()
		 if ($arena_continue==1) Then
			if ($arena_tier==2) Then
			   ;Send("9")
			   MouseClick("left", 386, 446)
			   Sleep(5000)
			   MouseClick("left", 413, 522);double check
			Elseif ($arena_tier==3) Then
			   MouseClick("left", 830, 510)
			   Sleep(5000)
			   MouseClick("left", 760, 508);double check
			Elseif ($arena_tier==4) Then ;arena tier 4
			   MouseClick("left", 433, 522);
			   Sleep(5000);
			Else

			   if (Not(getDominantColor(PixelGetColor(595,516))=="green") )Then; AND Not(getDominantColor(PixelGetColor(438,516))=="green")) Then; WHEN THERE ARE UPCOMING EVENT
				  MsgBox(0, "fight", "inside fight menu, not arena (special)", 1)
				  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
				  Sleep(1000)
				  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
				  Sleep(1000)
				  MouseClick("left", 500,446)
				  Local $wait = 0
				  do
					 Sleep(1000)
					 $wait = $wait+1
					 ;checkInsideFight()
				  Until (getDominantColor(PixelGetColor(595,516))=="green" OR ($wait>10))
				  MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
				  MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
				  Sleep(1000)
			   EndIf
			   checkInsideFight()
			   ;if (getDominantColor(PixelGetColor(438,516))=="green") Then ; WHEN THERE ARE UPCOMING EVENT
			   ;   MouseClick("left",438,516)
			   ;Else
				  MouseClick("left", 674, 508);
			   ;EndIf
			   Sleep(5000);
			EndIf
		 EndIf

		 checkInsideFight()
		 Sleep(5000)
		 Local $current_arena_tier  = $arena_tier

		 askForHelp()
		 checkInsideFight()
		 if ($arena_continue==1) Then
			; We have energy, continue;else change arena tier in next loop
			addToTeam()
			findMatch()
			fightArena()
		 EndIf
	  EndIf;if ($allstop==0) Then

   Until ($allstop==1)

   if ($quest_play) Then
	  questplay()
   EndIf
EndFunc

Func askForHelp()
   $status = "ask for help"
   Local $carryon = 1
   Do
	  checkInsideFight()
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			checkInsideFight()
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 2)
		 $arena_continue = 0
		 checkInsideFight()
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Elseif ($arena_tier==3) Then
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 1)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

   ;if we're in continue next fight
   if (getDominantColor(PixelGetColor(936,556))=="green") Then
	  if (PixelGetColor(688,436)==0x191e23) Then
		 $arena_continue = 0
		 fightArena()
	  EndIf
   EndIf
EndFunc

;arena
Func addToTeam()
   checkInsideFight()
   $status = "add to team"
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   checkInsideFight()
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   checkInsideFight()
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   $status = "find match"
   Sleep(500)
   MouseClick("left", 109, 547)

		 checkInsideFight()
   Sleep(4000)

   PixelSearch(543,416,575,429, 0x319732)
   if (@error) Then
	  ;highest is not easy, check if mid easy
	  PixelSearch(543,280,575,294, 0x319732)
	  if (@error) Then
		 ;mid is not easy
		 MsgBox(0,"tier", "mid and high is not easy",1)
		 MouseClick("left", 600,200)
	  Else
		 ;mid is easy
		 MouseClick("left", 600,320)
	  EndIf
   Else
	  ;highest is easy
	  MouseClick("left", 687, 445)
   EndIf

		 checkInsideFight()
   Sleep(3000)
   Send("0")
   $c = PixelGetColor(841,574)
   if (GetDominantColor($c)=="green") Then
	  Sleep(3000)
   Else
	  Local $t = 0
	  Local $cont = 1
	  Do
		 Sleep(500)
		 if ($t>120) Then
			;stuck
			$cont = 0
		 EndIf
		 if (Not(PixelGetColor(841,574)==$c)) Then
			$cont = 0
		 EndIf
		 $t = $t+1
	  Until ($cont==0)
   EndIf
EndFunc

;Fight in arena
Func fightArena()
   $status = "fight arena"
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 $stuqseq = 1
		 ;ToolTip("check stuck")
		 if (checkStuck()) Then
			updateCapture()
			$stop = 1
			MsgBox(0, "popup", "i guess we're stuck", 2)

			;stuck in leaderboard
			if (PixelGetColor(921,138)==0x292c30) Then
			   if (PixelGetColor(939,61)==0x6c6e71) Then
				  MsgBox(0, "popup", "leaderboard, ill close it", 1)
				  Sleep(2000)
				  MouseClick("left", 939,61)
				  Sleep(3000)
			   EndIf
			EndIf
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight

			Sleep(10000)
		 EndIf
		 updateCapture()

		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button? (loading screen)", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(1000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(1000)
			MouseClick("left", 270, 132) ;fight
			Sleep(5000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			MsgBox(0, "popup", "(view rewards) ?(TODO)", 1)
			Sleep(300)
			$arenatimersecond = 0
			if (getDominantColor(PixelGetColor(930,560))=="green") Then
			   $stop = 1
			   MouseClick("left", 57, 55); back
			   Sleep(5000)
			Else
			   Send("J")
			   MouseClick("left", 57, 55); back
			EndIf

			;
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 1);
			;$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 1);
			   ;$arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ;MsgBox(0, "dbg", StringFormat("%X", PixelGetColor(18,130)), 1)
	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
	  if (PixelGetColor(18, 130)==0x0b0b0c) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x0b0b0c) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding dark)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or the case we're in somewhere outside  (menu)
	  if (PixelGetColor(955,50)==0x2b2c30) Then
		 if (PixelGetColor(955, 562)==0x1d2630) Then
			if (Not(getDominantColor(PixelGetColor(936,556))=="green")) Then
			   $somewhereoutsidecounter = $somewhereoutsidecounter+1
			   if ($somewhereoutsidecounter>20) Then
				  MsgBox(0, "popup", "(somewhere outside for too long)", 2)
				  $stop = 1
				  Sleep(1000)
				  Send("J")
				  Sleep(1000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(1000)
				  MouseClick("left", 138, 58) ;menu double
				  Sleep(1000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(5000)
			   EndIf
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
	  ;quest completed!
	  Local $ca = PixelGetColor(204,190)
	  if ($ca==0x2b2c30) Then
		 Local $cb = PixelGetColor(739,514)
		 if ($cb==0x2b2c30) Then
			if (getDominantColor(PixelGetColor(310,485))=="green" AND getDominantColor(PixelGetColor(741,485))=="green") Then
			   MsgBox(0,"finished", "i'm going to press the mid button (replay/next)", 2)
			   Sleep(4000)
			   MouseClick("left", 500,470)
			   Sleep(1000)
			   MouseClick("left", 500,470)
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

Func questplay()
   $quest_stop = 0
   Do
	  MouseClick("left", 138, 58) ;menu
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 270, 132) ;fight
	  Sleep(500)
	  MouseClick("left", 270, 132) ;fight double
	  Sleep(10000)

	  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  Sleep(1000)
	  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  Sleep(1000)

	  MouseClick("left", 271,430);Event quest
	  Sleep(5000)

	  ;Event specific
	  MouseClick("left", 100,480)
	  Sleep(1000)
	  MouseClick("left", 100,480)
	  Sleep(3000)
	  MouseClick("left", 172,350)
	  Sleep(3000)
	  MouseClick("left", 384,294)
	  Sleep(3000)
	  MouseClick("left", 544,268)
	  ToolTip("3", 1000,100)
	  Sleep(3000)
	  ToolTip("2", 1000,100)
	  Sleep(3000)
	  ToolTip("1", 1000,100)
	  Sleep(3000)
	  MouseClick("left", 877,547)
	  ToolTip("3", 1000,100)
	  Sleep(3000)
	  ToolTip("2", 1000,100)
	  Sleep(3000)
	  ToolTip("1", 1000,100)
	  Sleep(3000)
	  fight();skip dialog until we can go to next node
	  nextNode()
	  ;end event specific

   Until ($quest_stop==0 OR $allstop==0)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 ;Check if out of energy
			if (checkEnergyIsEmpty()) Then
			   $arena_tier = 3
			   MsgBox(0,"out of energy", "my creator is away, i'll continue to arena to kill the time",2)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 270, 132) ;fight
			   Sleep(15000)
			   startArena()
			EndIf
		 ;End check
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf

	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(500)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)

	  ;out of energy
	  if (PixelGetColor(255,163)==0x2b2c30 AND PixelGetColor(720,165)==0x2b2c30) Then
		 ;ToolTip("masuk2")
		 ;ToolTip(StringFormat("%X",PixelGetColor(294,336)));help llogo
		 if (getDominantColor(PixelGetColor(294,336))=="red") Then
			;ToolTip("dapet")
			$stop = 1
			   ;Sleep(7000)
			   ;MsgBox(0,"finished", "finished", 2)
			   ;MouseClick("left", 300,475);back to quest button
			   ;Sleep(15000)
			MsgBox(0,"finished", "out of energy", 2)

			MsgBox(0,"out of energy", "my creator is away, i'll continue to arena to kill the time",2)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(15000)
			startArena()
		 EndIf
	  EndIf

	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

;check energy is full
Func checkEnergyIsFull()
   if Not(PixelGetColor(471,65)==0xffda59) Then ; check the energy logo is there
	  ToolTip("cant check energy", 1000,100)
	  Return False
   EndIf
   $energycolor = PixelGetColor(573,72)
   Local $red = BitShift($energycolor , 16)
   Local $green = BitShift(BitAND($energycolor , 0x00FF00), 8)
   Local $blue = BitAND($energycolor , 0x0000FF)
   if ( (($red-$green)>45) AND ($blue<6) ) Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc
;check energy is empty
Func checkEnergyIsEmpty()
   if Not(PixelGetColor(471,65)==0xffda59) Then ; check the energy logo is there
	  ToolTip("cant check energy", 1000,100)
	  Return False
   EndIf
   $energycolor = PixelGetColor(465,72)
   Local $red = BitShift($energycolor , 16)
   Local $green = BitShift(BitAND($energycolor , 0x00FF00), 8)
   Local $blue = BitAND($energycolor , 0x0000FF)
   if ( (($red-$green)>45) AND ($blue<6) ) Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc

;perform check if we're stuck in a room (any current click affects nothing)
;return True if stuck, False if not
Func checkStuck()
   ; check if we're stuck in some room
   $samepixel = 0
   if (Not(PixelGetColor(100,100)==$screensave[0])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(400,100)==$screensave[1])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,100)==$screensave[2])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(100,500)==$screensave[3])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(498,298)==$screensave[4])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,500)==$screensave[5])) Then
	  Return False
   EndIf
   Return True
EndFunc

;update $screensave to current capture
Func updateCapture()
   $screensave[0] = PixelGetColor(100,100)
   if ($screensave[0]==0x2a1a4c) Then ;we don't want to save loading screen;TODO REUPDATGE THESE
	  $screensave[0] = 0
   EndIf
   $screensave[1] = PixelGetColor(400,100)
   if ($screensave[1]==0x201641) Then
	  $screensave[1] = 0
   EndIf
   $screensave[2] = PixelGetColor(700,100)
   if ($screensave[2]==0x580e2f) Then
	  $screensave[2] = 0
   EndIf
   $screensave[3] = PixelGetColor(100,500)
   if ($screensave[3]==0x2f1661) Then
	  $screensave[3] = 0
   EndIf
   $screensave[4] = PixelGetColor(498,298)
   if ($screensave[4]==0x014cbe) Then
	  $screensave[4] = 0
   EndIf
   $screensave[5] = PixelGetColor(700,500)
   if ($screensave[5]==0x7d1852) Then
	  $screensave[5] = 0
   EndIf
EndFunc

Func checkInsideFight()
   if (isInsideFight()) Then
	  ;MsgBox(0,"fight", "inside FIGHT!",1)
	  ToolTip("inside fight",1000,0)
	  ;Sleep(500)
	  MouseClick("left",200,200)
	  MouseClick("left",220,200)
	  $arena_continue = 0
	  fightArena()
	  return 1
   Else
	  return 0
   EndIf
EndFunc
;Check if currently in fight
;return 1 if true, 0 false
Func isInsideFight()
   ;check if there is pause button
   Local $leftborder = 0
   Local $rightborder = 0
   $leftborder = PixelGetColor(466,57)
   $rightborder = PixelGetColor(511,57)
   if ($leftborder==0x222222 OR $leftborder==0x212121) Then
	  if ($rightborder==0x222222 OR $rightborder==0x212121) Then
		 if ((PixelGetColor(483,57)==0x9cba9b AND PixelGetColor(493,57)==0x9cba9b) AND getDominantColor(PixelGetColor(488,57))=="green") Then
			return 1
		 EndIf
	  EndIf
   EndIf
   return 0
EndFunc

Func Duel()
   Local $count=5;Limit count here
   Do
	  MouseClick("left", 276,97)
	  Sleep(1000)
	  Send("AquaticHornet");name to search
	  Sleep(1000)
	  MouseClick("left", 772,102);search button
	  Sleep(5000)
	  ;1nd search position
		 MouseClick("left", 286,186)
		 Sleep(1000)
		 MouseClick("left", 445,186)
		 Sleep(4000)
	  if False Then
	  ;2nd search position
		 MouseClick("left", 286,246)
		 Sleep(1000)
		 MouseClick("left", 445,246)
		 Sleep(4000)
	  EndIf
	  MouseClick("left", 616,453);continue
	  Sleep(4000)
	  MouseClick("left", 103,547);start
	  fightDuel()
	  Sleep(2000)
	  $count = $count - 1
   Until ($allstop==1 OR $count==0)
EndFunc

;Fight in duel
Func fightDuel()
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf
	  $loading = PixelGetColor(640, 540);
	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf
	  if (PixelGetColor(690,105)==0x161a1d AND PixelGetColor(800,105)==0x035d01 AND PixelGetColor(841,105)==0x515151) Then
		 MsgBox(0, "done", "done", 1)
		 Sleep(2000)
		 $stop = 1
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!h", "fightArena")
HotKeySet("+!q", "Duel")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")
HotKeySet("+!i", "showStatus")

Global $status="ngondek"
Global $savepixel = 0
Global $screensave[6]
$screensave[0] = 0
$screensave[1] = 0
$screensave[2] = 0
$screensave[3] = 0
$screensave[4] = 0
$screensave[5] = 0

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
;Flag whether to activate quest hunting mode (do quest if there are energy)
$quest_active = False
Do
   Sleep(1)
Until False

Func showStatus()
   ToolTip(StringFormat("%s", $status),1000,0)
EndFunc

Func idle()
   $status = "idle"
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Elseif ($arena_tier==3) Then
	  $arena_tier = 4
	  MsgBox(0, "arena tier", "arena tier is now alltier(when there is no event)", 2)
   ElseIf ($arena_tier==4) Then
	  $arena_tier = 5
	  MsgBox(0, "arena tier", "arena tier is now 5, the special high lvl arena(catalyst, alpha)", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $status = "start arena"
   $allstop = 0
   $quest_play = False
   $match_number = 0
   Do
	  calibrateWindow()
	  $match_number = $match_number + 1
	  if ($quest_active AND PixelGetColor(171,56)==0x5f5f62) Then ;quest is active, make sure not in fight and we can click menu
		 if (checkEnergyIsFull()) Then
			;to reduce stack memory we quit but set flag
			MsgBox(0, "quest", "i want to hunt ISOs", 2)
			$quest_play = True
			$allstop = 1
		 EndIf
	  EndIf

	  if (Mod($match_Number, 20)==0) Then

	  EndIf

	  $arena_continue = 1
	  if ($allstop==0) Then
		 checkInsideFight()
		 Sleep(500)
		 if ($arena_tier==5) Then
			MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			Sleep(500)
			MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			Sleep(500)
		 Else
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			checkInsideFight()
			Sleep(1500)
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
		 EndIf
		 checkInsideFight()
		 Sleep(1000)

		 checkInsideFight()

		 if (Not(getDominantColor(PixelGetColor(346,535))=="green") AND (Not($arena_tier==5))) Then
			MsgBox(0, "fight", "inside fight menu, not arena", 1)
			MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			Sleep(400)
			MouseClick("left", 500,446)
			Sleep(2000)
			Local $wait = 0
			do
			   Sleep(1000)
			   $wait = $wait+1
			   checkInsideFight()
			Until (getDominantColor(PixelGetColor(435,525))=="green" OR ($wait>10))
		 EndIf
		 checkInsideFight()
		 ;check if currently in one of 3 fights
		 if (PixelGetColor(160,222)==0x2b2c30 AND PixelGetColor(816,222)==0x2b2c30) Then
			Local $leftresult=PixelGetColor(294,280) ;lose 721a1a red, win 26552e
			Local $rightresult=PixelGetColor(697,280)
			if ($leftresult==0x26552e OR $leftresult==0x721a1a) Then
			   if ($rightresult==0x26552e OR $rightresult==0x721a1a) Then
				  MsgBox(0, "fight", "more fight to go", 1)
				  Sleep(1000)
				  MouseClick("left", 200,200)
				  fightArena()
				  $arena_continue = 0
			   EndIf
			EndIf
		 EndIf
		 checkInsideFight()
		 if ($arena_continue==1) Then
			if ($arena_tier==2) Then
			   ;Send("9")
			   MouseClick("left", 386, 446)
			   Sleep(5000)
			   MouseClick("left", 413, 522);double check
			Elseif ($arena_tier==3) Then
			   MouseClick("left", 830, 510)
			   Sleep(5000)
			   MouseClick("left", 760, 508);double check
			Elseif ($arena_tier==4) Then ;arena tier 4
			   MouseClick("left", 433, 522);
			   Sleep(5000);
			Else

			   if (Not(getDominantColor(PixelGetColor(595,516))=="green") )Then; AND Not(getDominantColor(PixelGetColor(438,516))=="green")) Then; WHEN THERE ARE UPCOMING EVENT
				  MsgBox(0, "fight", "inside fight menu, not arena (special)", 1)
				  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
				  Sleep(1000)
				  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
				  Sleep(1000)
				  MouseClick("left", 500,446)
				  Local $wait = 0
				  do
					 Sleep(1000)
					 $wait = $wait+1
					 ;checkInsideFight()
				  Until (getDominantColor(PixelGetColor(595,516))=="green" OR ($wait>10))
				  MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
				  MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
				  Sleep(1000)
			   EndIf
			   checkInsideFight()
			   ;if (getDominantColor(PixelGetColor(438,516))=="green") Then ; WHEN THERE ARE UPCOMING EVENT
			   ;   MouseClick("left",438,516)
			   ;Else
				  MouseClick("left", 674, 508);
			   ;EndIf
			   Sleep(5000);
			EndIf
		 EndIf

		 checkInsideFight()
		 Sleep(5000)
		 Local $current_arena_tier  = $arena_tier

		 askForHelp()
		 checkInsideFight()
		 if ($arena_continue==1) Then
			; We have energy, continue;else change arena tier in next loop
			addToTeam()
			findMatch()
			fightArena()
		 EndIf
	  EndIf;if ($allstop==0) Then
   Until ($allstop==1)

   if ($quest_play) Then
	  questplay()
   EndIf
EndFunc

Func askForHelp()
   $status = "ask for help"
   Local $carryon = 1
   Do
	  checkInsideFight()
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			checkInsideFight()
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 2)
		 $arena_continue = 0
		 checkInsideFight()
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Elseif ($arena_tier==3) Then
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 1)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

   ;if we're in continue next fight
   if (getDominantColor(PixelGetColor(936,556))=="green") Then
	  if (PixelGetColor(688,436)==0x191e23) Then
		 $arena_continue = 0
		 fightArena()
	  EndIf
   EndIf
EndFunc

;arena
Func addToTeam()
   checkInsideFight()
   $status = "add to team"
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   checkInsideFight()
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   checkInsideFight()
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   $status = "find match"
   Sleep(500)
   MouseClick("left", 109, 547)

		 checkInsideFight()
   Sleep(4000)

   PixelSearch(543,416,575,429, 0x319732)
   if (@error) Then
	  ;highest is not easy, check if mid easy
	  PixelSearch(543,280,575,294, 0x319732)
	  if (@error) Then
		 ;mid is not easy
		 MsgBox(0,"tier", "mid and high is not easy",1)
		 MouseClick("left", 600,200)
	  Else
		 ;mid is easy
		 MouseClick("left", 600,320)
	  EndIf
   Else
	  ;highest is easy
	  MouseClick("left", 687, 445)
   EndIf

		 checkInsideFight()
   Sleep(3000)
   Send("0")
   $c = PixelGetColor(841,574)
   if (GetDominantColor($c)=="green") Then
	  Sleep(3000)
   Else
	  Local $t = 0
	  Local $cont = 1
	  Do
		 Sleep(500)
		 if ($t>120) Then
			;stuck
			$cont = 0
		 EndIf
		 if (Not(PixelGetColor(841,574)==$c)) Then
			$cont = 0
		 EndIf
		 $t = $t+1
	  Until ($cont==0)
   EndIf
EndFunc

;Fight in arena
Func fightArena()
   $status = "fight arena"
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 $stuqseq = 1
		 ;ToolTip("check stuck")
		 if (checkStuck()) Then
			updateCapture()
			$stop = 1
			MsgBox(0, "popup", "i guess we're stuck", 2)

			;stuck in leaderboard
			if (PixelGetColor(921,138)==0x292c30) Then
			   if (PixelGetColor(939,61)==0x6c6e71) Then
				  MsgBox(0, "popup", "leaderboard, ill close it", 1)
				  Sleep(2000)
				  MouseClick("left", 939,61)
				  Sleep(3000)
			   EndIf
			EndIf
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight

			Sleep(10000)
		 EndIf
		 updateCapture()

		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button? (loading screen)", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(1000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(1000)
			MouseClick("left", 270, 132) ;fight
			Sleep(5000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			MsgBox(0, "popup", "(view rewards) ?(TODO)", 1)
			Sleep(300)
			$arenatimersecond = 0
			if (getDominantColor(PixelGetColor(930,560))=="green") Then
			   $stop = 1
			   MouseClick("left", 57, 55); back
			   Sleep(5000)
			Else
			   Send("J")
			   MouseClick("left", 57, 55); back
			EndIf

			;
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 1);
			;$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 1);
			   ;$arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ;MsgBox(0, "dbg", StringFormat("%X", PixelGetColor(18,130)), 1)
	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
	  if (PixelGetColor(18, 130)==0x0b0b0c) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x0b0b0c) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding dark)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or the case we're in somewhere outside  (menu)
	  if (PixelGetColor(955,50)==0x2b2c30) Then
		 if (PixelGetColor(955, 562)==0x1d2630) Then
			if (Not(getDominantColor(PixelGetColor(936,556))=="green")) Then
			   $somewhereoutsidecounter = $somewhereoutsidecounter+1
			   if ($somewhereoutsidecounter>20) Then
				  MsgBox(0, "popup", "(somewhere outside for too long)", 2)
				  $stop = 1
				  Sleep(1000)
				  Send("J")
				  Sleep(1000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(1000)
				  MouseClick("left", 138, 58) ;menu double
				  Sleep(1000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(5000)
			   EndIf
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
	  ;quest completed!
	  Local $ca = PixelGetColor(204,190)
	  if ($ca==0x2b2c30) Then
		 Local $cb = PixelGetColor(739,514)
		 if ($cb==0x2b2c30) Then
			if (getDominantColor(PixelGetColor(310,485))=="green" AND getDominantColor(PixelGetColor(741,485))=="green") Then
			   MsgBox(0,"finished", "i'm going to press the mid button (replay/next)", 2)
			   Sleep(4000)
			   MouseClick("left", 500,470)
			   Sleep(1000)
			   MouseClick("left", 500,470)
			EndIf
		 EndIf
	  EndIf

	  ;out of energy
	  if (PixelGetColor(255,163)==0x2b2c30 AND PixelGetColor(720,165)==0x2b2c30) Then
		 PixelSearch(151,105,771,518, 0x771100)
		 if (Not(@error)) Then
			$stop = 1
			   ;Sleep(7000)
			   ;MsgBox(0,"finished", "finished", 2)
			   ;MouseClick("left", 300,475);back to quest button
			   ;Sleep(15000)
			MsgBox(0,"finished", "out of energy", 2)

			MsgBox(0,"out of energy", "my creator is away, i'll continue to arena to kill the time",2)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(15000)
			startArena()
		 EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

Func questplay()
   $quest_stop = 0
   Do
	  MouseClick("left", 138, 58) ;menu
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 138, 58) ;menu double
	  Sleep(1000)
	  MouseClick("left", 270, 132) ;fight
	  Sleep(500)
	  MouseClick("left", 270, 132) ;fight double
	  Sleep(10000)

	  MouseClick("left", 271,430);Event quest
	  Sleep(5000)

	  ;Event specific
	  MouseClick("left", 100,480)
	  Sleep(1000)
	  MouseClick("left", 100,480)
	  Sleep(3000)
	  MouseClick("left", 172,350)
	  Sleep(3000)
	  MouseClick("left", 384,294)
	  Sleep(3000)
	  MouseClick("left", 544,268)
	  ToolTip("3", 1000,100)
	  Sleep(3000)
	  ToolTip("2", 1000,100)
	  Sleep(3000)
	  ToolTip("1", 1000,100)
	  Sleep(3000)
	  MouseClick("left", 877,547)
	  ToolTip("3", 1000,100)
	  Sleep(3000)
	  ToolTip("2", 1000,100)
	  Sleep(3000)
	  ToolTip("1", 1000,100)
	  Sleep(3000)
	  fight();skip dialog until we can go to next node
	  nextNode()
	  ;end event specific

   Until ($quest_stop==0 OR $allstop==0)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 ;Check if out of energy
			if (checkEnergyIsEmpty()) Then
			   $arena_tier = 3
			   MsgBox(0,"out of energy", "my creator is away, i'll continue to arena to kill the time",2)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 148, 58) ;menu
			   Sleep(2000)
			   MouseClick("left", 270, 132) ;fight
			   Sleep(15000)
			   startArena()
			EndIf
		 ;End check
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf

	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(500)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)
	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

;check energy is full
Func checkEnergyIsFull()
   if Not(PixelGetColor(471,65)==0xffda59) Then ; check the energy logo is there
	  ToolTip("cant check energy", 1000,100)
	  Return False
   EndIf
   $energycolor = PixelGetColor(573,72)
   Local $red = BitShift($energycolor , 16)
   Local $green = BitShift(BitAND($energycolor , 0x00FF00), 8)
   Local $blue = BitAND($energycolor , 0x0000FF)
   if ( (($red-$green)>45) AND ($blue<6) ) Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc
;check energy is empty
Func checkEnergyIsEmpty()
   if Not(PixelGetColor(471,65)==0xffda59) Then ; check the energy logo is there
	  ToolTip("cant check energy", 1000,100)
	  Return False
   EndIf
   $energycolor = PixelGetColor(465,72)
   Local $red = BitShift($energycolor , 16)
   Local $green = BitShift(BitAND($energycolor , 0x00FF00), 8)
   Local $blue = BitAND($energycolor , 0x0000FF)
   if ( (($red-$green)>45) AND ($blue<6) ) Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc

;perform check if we're stuck in a room (any current click affects nothing)
;return True if stuck, False if not
Func checkStuck()
   ; check if we're stuck in some room
   $samepixel = 0
   if (Not(PixelGetColor(100,100)==$screensave[0])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(400,100)==$screensave[1])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,100)==$screensave[2])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(100,500)==$screensave[3])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(498,298)==$screensave[4])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,500)==$screensave[5])) Then
	  Return False
   EndIf
   Return True
EndFunc

;update $screensave to current capture
Func updateCapture()
   $screensave[0] = PixelGetColor(100,100)
   if ($screensave[0]==0x2a1a4c) Then ;we don't want to save loading screen;TODO REUPDATGE THESE
	  $screensave[0] = 0
   EndIf
   $screensave[1] = PixelGetColor(400,100)
   if ($screensave[1]==0x201641) Then
	  $screensave[1] = 0
   EndIf
   $screensave[2] = PixelGetColor(700,100)
   if ($screensave[2]==0x580e2f) Then
	  $screensave[2] = 0
   EndIf
   $screensave[3] = PixelGetColor(100,500)
   if ($screensave[3]==0x2f1661) Then
	  $screensave[3] = 0
   EndIf
   $screensave[4] = PixelGetColor(498,298)
   if ($screensave[4]==0x014cbe) Then
	  $screensave[4] = 0
   EndIf
   $screensave[5] = PixelGetColor(700,500)
   if ($screensave[5]==0x7d1852) Then
	  $screensave[5] = 0
   EndIf
EndFunc

Func checkInsideFight()
   if (isInsideFight()) Then
	  ;MsgBox(0,"fight", "inside FIGHT!",1)
	  ToolTip("inside fight",1000,0)
	  ;Sleep(500)
	  MouseClick("left",200,200)
	  MouseClick("left",220,200)
	  $arena_continue = 0
	  fightArena()
	  return 1
   Else
	  return 0
   EndIf
EndFunc
;Check if currently in fight
;return 1 if true, 0 false
Func isInsideFight()
   ;check if there is pause button
   Local $leftborder = 0
   Local $rightborder = 0
   $leftborder = PixelGetColor(466,57)
   $rightborder = PixelGetColor(511,57)
   if ($leftborder==0x222222 OR $leftborder==0x212121) Then
	  if ($rightborder==0x222222 OR $rightborder==0x212121) Then
		 if ((PixelGetColor(483,57)==0x9cba9b AND PixelGetColor(493,57)==0x9cba9b) AND getDominantColor(PixelGetColor(488,57))=="green") Then
			return 1
		 EndIf
	  EndIf
   EndIf
   return 0
EndFunc

Func Duel()
   Local $count=5;Limit count here
   Do
	  MouseClick("left", 276,97)
	  Sleep(1000)
	  Send("AquaticHornet");name to search
	  Sleep(1000)
	  MouseClick("left", 772,102);search button
	  Sleep(5000)
	  ;1nd search position
		 MouseClick("left", 286,186)
		 Sleep(1000)
		 MouseClick("left", 445,186)
		 Sleep(4000)
	  if False Then
	  ;2nd search position
		 MouseClick("left", 286,246)
		 Sleep(1000)
		 MouseClick("left", 445,246)
		 Sleep(4000)
	  EndIf
	  MouseClick("left", 616,453);continue
	  Sleep(4000)
	  MouseClick("left", 103,547);start
	  fightDuel()
	  Sleep(2000)
	  $count = $count - 1
   Until ($allstop==1 OR $count==0)
EndFunc

;Fight in duel
Func fightDuel()
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf
	  $loading = PixelGetColor(640, 540);
	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf
	  if (PixelGetColor(690,105)==0x161a1d AND PixelGetColor(800,105)==0x035d01 AND PixelGetColor(841,105)==0x515151) Then
		 MsgBox(0, "done", "done", 1)
		 Sleep(2000)
		 $stop = 1
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc


Update GuiCreateEx.au3

Update GuiCreateEx.au3

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>

OnAutoItExitRegister("_GUICreateEx_OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $g__aGuiCreateEx[1] = [0]

#cs
; Example
#include-once
#include <GuiCreateEx.au3>

Global $hGui
Global $hButton_NewGui

$hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", 800, 600)
$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func NewGui()
	Local $aSize = WinGetPos($g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	Local $hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", $aSize[2] - (20 + 6), $aSize[3] - (40 + 5), $aSize[0] + 10, $aSize[1] + 10, Default, Default, $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
	GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
	GUISetState(@SW_SHOW, $hGui)
EndFunc   ;==>NewGui
#ce

; #FUNCTION# ====================================================================================================================
; Name...........:	GUICreateEx
; Description ...:	Allow create a new GUI (Graphic User Interface) above current GUI and lock previus GUI
; Syntax.........:	same way of GuiCreate
; Parameters ....:	$sTitle.......: Title's GUI
;					$iWidth.......:	width's GUI
;					$iHeight......: height's GUI
;					$iLeft........:	left position's GUI
; 					$iTop.........: top position's GUI
;					$mStyle.......:	Style's GUI
;					$mExStyle.....:	Extended Style's GUI
;					$iParent......: The handle of another previously created window
; Return values .:	a windows handle
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Remarks .......:
; Related .......:
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; Example .......:
; ===============================================================================================================================
Func GUICreateEx($sTitle = "", $iWidth = 460, $iHeight = 360, $iLeft = -1, $iTop = -1, $mStyle = Default, $mExStyle = Default, $iParent = 0)
	If Not $g__aGuiCreateEx[0] Then
		$iParent = 0
	Else
		$iParent = $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1]
		GUISetState(@SW_DISABLE, $iParent)
	EndIf
	Local $hGui = GUICreate($sTitle, $iWidth, $iHeight, $iLeft, $iTop, $mStyle, $mExStyle, $iParent)
	If @error Then Return SetError(1, 0, 0)
	GUISetOnEvent($GUI_EVENT_CLOSE, "_GUICreateEx_Quit")
	_ArrayAdd($g__aGuiCreateEx, $hGui)
	$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	Return $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
EndFunc   ;==>GUICreateEx

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_OnExit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_OnExit()
	GUISetState($g__aGuiCreateEx[1], @SW_HIDE)
	GUIDelete($g__aGuiCreateEx[1])
EndFunc   ;==>_GUICreateEx_OnExit

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_Quit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_Quit()
	Local $hGui
	Switch $g__aGuiCreateEx[0]
		Case 1
			$hGui = $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
			Exit
		Case Else
			GUISetState(@SW_ENABLE, $g__aGuiCreateEx[$g__aGuiCreateEx[0] - 1])
			GUISetState($g__aGuiCreateEx[$g__aGuiCreateEx[0]], @SW_HIDE)
			GUIDelete($g__aGuiCreateEx[$g__aGuiCreateEx[0]])
			_ArrayDelete($g__aGuiCreateEx, UBound($g__aGuiCreateEx, 1) - 1)
			$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	EndSwitch
EndFunc   ;==>_GUICreateEx_Quit

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>

OnAutoItExitRegister("_GUICreateEx_OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $g__aGuiCreateEx[1] = [0]

#cs
; Example
#include-once
#include <GuiCreateEx.au3>

Global $hGui
Global $hButton_NewGui

$hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", 800, 600)
$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func NewGui()
	Local $aSize = WinGetPos($g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	Local $hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", $aSize[2] - (20 + 6), $aSize[3] - (40 + 5), $aSize[0] + 10, $aSize[1] + 10, Default, Default, $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
	GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
	GUISetState(@SW_SHOW, $hGui)
EndFunc   ;==>NewGui
#ce

; #FUNCTION# ====================================================================================================================
; Name...........:	GUICreateEx
; Description ...:	Allow create a new GUI (Graphic User Interface) above current GUI and lock previus GUI
; Syntax.........:	same way of GuiCreate
; Parameters ....:	$sTitle.......: Title's GUI
;					$iWidth.......:	width's GUI
;					$iHeight......: height's GUI
;					$iLeft........:	left position's GUI
; 					$iTop.........: top position's GUI
;					$mStyle.......:	Style's GUI
;					$mExStyle.....:	Extended Style's GUI
;					$iParent......: The handle of another previously created window
; Return values .:	a windows handle
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Remarks .......:
; Related .......:
; Link ..........:	https://github.com/chechelaky/AutoIt/blob/master/GuiCreateEx/GuiCreateEx.au3
; Example .......:
; ===============================================================================================================================
Func GUICreateEx($sTitle = "", $iWidth = 460, $iHeight = 360, $iLeft = -1, $iTop = -1, $mStyle = Default, $mExStyle = Default, $iParent = 0)
	If Not $g__aGuiCreateEx[0] Then
		$iParent = 0
	Else
		$iParent = $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1]
		GUISetState(@SW_DISABLE, $iParent)
	EndIf
	Local $hGui = GUICreate($sTitle, $iWidth, $iHeight, $iLeft, $iTop, $mStyle, $mExStyle, $iParent)
	If @error Then Return SetError(1, 0, 0)
	GUISetOnEvent($GUI_EVENT_CLOSE, "_GUICreateEx_Quit")
	_ArrayAdd($g__aGuiCreateEx, $hGui)
	$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	Return $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
EndFunc   ;==>GUICreateEx

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_OnExit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/blob/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_OnExit()
	GUISetState($g__aGuiCreateEx[1], @SW_HIDE)
	GUIDelete($g__aGuiCreateEx[1])
EndFunc   ;==>_GUICreateEx_OnExit

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_Quit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/blob/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_Quit()
	Local $hGui
	Switch $g__aGuiCreateEx[0]
		Case 1
			$hGui = $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
			Exit
		Case Else
			GUISetState(@SW_ENABLE, $g__aGuiCreateEx[$g__aGuiCreateEx[0] - 1])
			GUISetState($g__aGuiCreateEx[$g__aGuiCreateEx[0]], @SW_HIDE)
			GUIDelete($g__aGuiCreateEx[$g__aGuiCreateEx[0]])
			_ArrayDelete($g__aGuiCreateEx, UBound($g__aGuiCreateEx, 1) - 1)
			$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	EndSwitch
EndFunc   ;==>_GUICreateEx_Quit