Search code examples
pythonpython-3.xkeypresssimulate

Trying to using python for controlling games


I'm trying to use Python with win32api for controlling a game(Maplestory).My script runs perfectly on a lot of software such as Notepad, but except game.

I think maybe the game communicate directly with the hardware so that I could't use win32api to controlling game. But I can't figure out how to communicate with the hardware using a Python script. And I also didn't know who wrote a wheel could communicate with keyboard hardware.

These is my script:

import time,random,win32con,win32api

WAIT_TIME = 5

key_map = {
    "0": 49, "1": 50, "2": 51, "3": 52, "4": 53, "5": 54, "6": 55, "7": 56, "8": 57, "9": 58,
    "A": 65, "B": 66, "C": 67, "D": 68, "E": 69, "F": 70, "G": 71, "H": 72, "I": 73, "J": 74,
    "K": 75, "L": 76, "M": 77, "N": 78, "O": 79, "P": 80, "Q": 81, "R": 82, "S": 83, "T": 84,
    "U": 85, "V": 86, "W": 87, "X": 88, "Y": 89, "Z": 90
}

class Press:
    def __init__(self):
        print("The program will start in %d seconds" % WAIT_TIME)
        time.sleep(WAIT_TIME)
        self.time = time.time()
        pass

    def key_down(self, key):
        key = key.upper()
        vk_code = key_map[key]
        win32api.keybd_event(vk_code,win32api.MapVirtualKey(vk_code,0),0,0)


    def key_up(self, key):
        key = key.upper()
        vk_code = key_map[key]
        win32api.keybd_event(vk_code, win32api.MapVirtualKey(vk_code, 0), win32con.KEYEVENTF_KEYUP, 0)


    def key_press(self, key):
        self.key_down(key)
        time.sleep(0.02)
        self.key_up(key)
        print(key)



class Illium(Press):
    def __init__(self):
        super().__init__()
        self.spear = "A"
        self.bullet = "Q"
        self.buff1 = "3"
        self.buff2 = "4"

    def add_buff(self):
        if time.time() - self.time > 60:
            self.key_press(self.buff1)
            time.sleep(0.5)
            self.key_press(self.buff2)
            time.sleep(random.uniform(0.5,1))
            self.key_press("1")   # 
            self.time = time.time()

    def auto_attack(self):
        self.add_buff()
        time.sleep(random.uniform(0.5,1))  
        self.key_press(self.spear)
        time.sleep(random.uniform(1,1.5))
        self.key_press(self.bullet)
        time.sleep(random.uniform(0.5,1))




illium = Illium()
while True:
    illium.auto_attack()
    time.sleep(random.uniform(0.5,1))


print("ENd")

Solution

  • Some games will take some measures to prevent script running(to prevent cheating). Maybe using python script is not a good idea.

    I don not play this game.If you really want to use python,maybe you can try other modules to control the game(such as pynput,pykeyboard and so on).