Reklam
from threading import Thread
from ahk import AHK
import ctypes
import cv2, pytesseract
import win32gui
import time
from PIL import ImageGrab, Image
import numpy as np
import sys
from difflib import SequenceMatcher
import re
class Agent:
def __init__(self):
self.state = 'init'
self.ahk = AHK()
self.win = self.ahk.find_window(title='Knight OnLine Client')
self.win.activate()
self.full_hp = None
self.full_mp = None
self.target_monster = False
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
self.window_info = {}
win32gui.EnumWindows(self.set_window_coordinates, self.window_info)
@staticmethod
def get_screen(x1, y1, x2, y2):
box = (x1, y1, x2, y2)
screen = ImageGrab.grab(box)
img = np.array(screen.getdata(), dtype=np.uint8).reshape((screen.size[1], screen.size[0], 3))
return img
def set_target(self):
if self.state == 'init' or self.state == 'onhold' or self.state == 'toofar':
self.ahk.key_press('z')
if self.target_monster and self.state != 'toofar':
self.start_attack()
def set_window_coordinates(self, hwnd, window_info):
if win32gui.IsWindowVisible(hwnd):
if 'Knight' in win32gui.GetWindowText(hwnd):
rect = win32gui.GetWindowRect(hwnd)
x = rect[0]
y = rect[1]
w = rect[2] - x
h = rect[3] - y
window_info['x'] = x
window_info['y'] = y
window_info['width'] = w
window_info['height'] = h
window_info['name'] = win32gui.GetWindowText(hwnd)
win32gui.SetForegroundWindow(hwnd)
def check_target(self, monster):
x1, y1, x2, y2 = self.window_info['x'], self.window_info['y'], self.window_info['width'], self.window_info['height']
cut_w = x2 / 2
cut_re = 110
cut_h = y2 - 47
x1 = x1 + cut_w - cut_re
x2 = x1 + (cut_re * 2)
img = Agent.get_screen(x1, y1+10, x2, y2-cut_h)
img = cv2.resize(img, (550, 150))
img = cv2.copyMakeBorder(img, 10, 10, 0, 0, cv2.BORDER_CONSTANT, value=255)
imagesave = Image.fromarray(img, mode="RGB")
imagesave.save("image.png")
gray = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGR2GRAY)
# Performing OTSU threshold
_, thresh2 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY)
_, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
config = ('-l eng --oem 1 --psm 3')
text1 = pytesseract.image_to_string(thresh1, config=config).lower().strip()
text2 = pytesseract.image_to_string(thresh2, config=config).lower().strip()
print(f"OCR Text1: '{text1}'") # Debug
print(f"OCR Text2: '{text2}'") # Debug
print(f"Aranan monster: '{monster.lower()}'") # Debug
assert type(monster) == str, "Not correct variable type for monster."
if SequenceMatcher(None, monster.lower(), text1).ratio() > .5 or SequenceMatcher(None, monster.lower(), text2).ratio() > .5:
self.target_monster = True
self.state = 'init' # ✅ Bu satır eklendi!
print(f"✅ Hedef bulundu! State: {self.state}")
else:
self.target_monster = False
self.state = 'onhold'
print(f"❌ Hedef yok, state: {self.state}")
def check_stats(self, stat_name):
if stat_name == 'hp':
x1, y1, x2, y2 = 124, 49, 196, 61
if stat_name == 'mp':
x1, y1, x2, y2 = 124, 71, 196, 81
img = Agent.get_screen(x1, y1, x2, y2)
img = cv2.resize(img, (350, 55))
img = cv2.copyMakeBorder(img, 10, 10, 0, 0, cv2.BORDER_CONSTANT, value=255)
gray = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGR2GRAY)
_, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
config = ('-l eng --oem 1 --psm 3')
text = pytesseract.image_to_string(thresh1, config=config)
text = text.split('/')
text[0] = re.findall('[0-9]+', text[0])
text[1] = re.findall('[0-9]+', text[1])
return int(text[0][0]), int(text[1][0])
def check_toofar(self):
x1, y1, x2, y2 = 1532, 955, 1871, 977
img = Agent.get_screen(x1, y1, x2, y2)
img = cv2.resize(img, (350, 55))
gray = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGR2GRAY)
_, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
config = ('-l eng --oem 1 --psm 3')
text = pytesseract.image_to_string(thresh1, config=config)
if 'too far' in text.lower() and self.state != 'toofar':
self.state = 'toofar'
print("Too Far tespit edildi!")
self.set_target()
elif 'too far' in text.lower() and self.state == 'toofar':
self.state = 'onhold'
self.set_target()
def spell_mana(self, act, shld, th):
if act / shld < th:
self.ahk.key_press('2')
print(f"Mana kullanıldı: {act}/{shld}")
def spell_hp(self, act, shld, th):
if act / shld < th:
self.ahk.key_press('1')
print(f"HP kullanıldı: {act}/{shld}")
def start_attack(self):
print("Saldırı başlatılıyor...")
i = 0
while i < 3:
self.ahk.key_press('9')
time.sleep(.8)
i += 1
self.state = 'attacking'
print("Saldırı durumuna geçildi!")
def attack(self, attack_type):
print(f'State = {self.state}, Target = {self.target_monster}')
if self.state == 'attacking':
try:
act_hp, shld_hp = self.check_stats('hp')
act_mp, shld_mp = self.check_stats('mp')
self.spell_hp(act_hp, shld_hp, .35)
self.spell_mana(act_mp, shld_mp, .1)
self.ahk.key_press(attack_type)
except Exception as e:
print(f"Stat kontrol hatası: {e}")
elif self.state == 'onhold' or self.state == 'init':
if self.target_monster:
print("Hedef var, saldırı başlatılıyor...")
self.start_attack()
else:
print("Hedef aranıyor...")
self.set_target()
def recurrent(self, key):
self.ahk.key_press(key)
def active_win(self):
return self.ahk.active_window
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def cont_attack(stop, attack_type):
while True:
try:
active_window = bot.active_win().title
if 'Knight OnLine Client' in str(active_window):
time.sleep(.05)
bot.attack(attack_type)
if stop():
break
except Exception as e:
print(f"Attack loop error: {e}")
time.sleep(1)
def check_target_loop(monster, stop):
while True:
try:
bot.check_toofar()
bot.check_target(monster)
time.sleep(0.3) # CPU kullanımını azalt
if stop():
break
except Exception as e:
print(f"Target check error: {e}")
time.sleep(1)
def reccurent_skills(key, stop, t=None):
while True:
try:
active_window = bot.active_win().title
if 'Knight OnLine Client' in str(active_window):
if t is not None:
bot.recurrent(str(key))
time.sleep(t)
else:
bot.recurrent(str(key))
time.sleep(0.05)
except Exception as e:
print(f"Skill loop error: {e}")
time.sleep(1)
if stop():
break
if __name__ == '__main__':
if is_admin():
try:
bot = Agent()
print("✅ Bot başarıyla başlatıldı!")
print("Komutlar: att start, att stop, lf start, lf stop, wolf start, wolf stop, safety start, safety stop")
print("=" * 50)
# Global thread variables
att_stop = False
ct_stop = False
lf_stop = False
wolf_stop = False
safety_stop = False
att_thread = None
ct_thread = None
lf_thread = None
wolf_thread = None
safety_thread = None
while True:
action = input('\nAksiyon Gir: ').strip().lower()
if action == 'att start':
# Önceki attack thread'leri durdur
if att_thread and att_thread.is_alive():
att_stop = True
ct_stop = True
att_thread.join()
if ct_thread:
ct_thread.join()
monster = input('Hedef yaratık adı: ')
attack_type = input('Saldırı tuşu (varsayılan 9): ') or '9'
att_stop = False
ct_stop = False
att_thread = Thread(target=cont_attack, args=[lambda: att_stop, attack_type])
ct_thread = Thread(target=check_target_loop, args=[monster, lambda: ct_stop])
ct_thread.start()
att_thread.start()
print(f"✅ Saldırı başlatıldı - Monster: {monster}, Skill: {attack_type}")
elif action == 'att stop':
att_stop = True
ct_stop = True
if att_thread:
att_thread.join()
if ct_thread:
ct_thread.join()
print("✅ Saldırı durduruldu")
elif action == 'lf start':
if lf_thread and lf_thread.is_alive():
lf_stop = True
lf_thread.join()
lf_stop = False
lf_thread = Thread(target=reccurent_skills, args=[6, lambda: lf_stop])
lf_thread.start()
print("✅ Life Force başlatıldı")
elif action == 'lf stop':
lf_stop = True
if lf_thread:
lf_thread.join()
print("✅ Life Force durduruldu")
elif action == 'wolf start':
if wolf_thread and wolf_thread.is_alive():
wolf_stop = True
wolf_thread.join()
wolf_stop = False
wolf_thread = Thread(target=reccurent_skills, args=[8, lambda: wolf_stop, 121])
wolf_thread.start()
print("✅ Wolf başlatıldı")
elif action == 'wolf stop':
wolf_stop = True
if wolf_thread:
wolf_thread.join()
print("✅ Wolf durduruldu")
elif action == 'safety start':
if safety_thread and safety_thread.is_alive():
safety_stop = True
safety_thread.join()
safety_stop = False
safety_thread = Thread(target=reccurent_skills, args=[7, lambda: safety_stop])
safety_thread.start()
print("✅ Safety başlatıldı")
elif action == 'safety stop':
safety_stop = True
if safety_thread:
safety_thread.join()
print("✅ Safety durduruldu")
elif action == 'exit':
# Tüm thread'leri durdur
att_stop = True
ct_stop = True
lf_stop = True
wolf_stop = True
safety_stop = True
for thread in [att_thread, ct_thread, lf_thread, wolf_thread, safety_thread]:
if thread and thread.is_alive():
thread.join()
print("✅ Bot kapatıldı")
break
else:
print("❌ Geçersiz komut!")
except KeyboardInterrupt:
print("\n⚠️ Program kullanıcı tarafından durduruldu")
except Exception as e:
print(f"❌ Program hatası: {e}")
else:
# Admin yetkileri ile yeniden başlat
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)