杰瑞科技汇

如何用Python实现DirectInput?

Of course! Let's dive into using DirectInput with Python.

如何用Python实现DirectInput?-图1
(图片来源网络,侵删)

The Core Concept: pydirectinput

For Python, the most popular and reliable library for emulating DirectInput (and other input methods) is pydirectinput.

It's a powerful cross-platform library that can:

  • Move the mouse and click.
  • Type text and press keys.
  • Scroll the mouse wheel.
  • Control the keyboard and mouse in a way that most games and applications detect as real input.

It works by sending low-level OS-level input commands, making it much more effective than simple GUI automation tools like pyautogui for gaming.


Installation

First, you need to install the library. Open your terminal or command prompt and run:

如何用Python实现DirectInput?-图2
(图片来源网络,侵删)
pip install pydirectinput

Basic Usage: Mouse and Keyboard

Here are the most common functions you'll use.

Mouse Functions

import pydirectinput
import time
# --- Mouse Movement ---
# Move the mouse to a specific coordinate (x, y)
pydirectinput.moveTo(100, 200)
# Move the mouse relative to its current position
pydirectinput.moveRel(50, -30)  # Move right 50 pixels, up 30 pixels
# --- Mouse Clicks ---
# Left click
pydirectinput.click()
# Right click
pydirectinput.rightClick()
# Middle click
pydirectinput.middleClick()
# Click a specific button
pydirectinput.click(button='x1') # For a side mouse button
# --- Mouse Dragging ---
# Click and hold, move, then release
pydirectinput.mouseDown() # Or mouseDown(button='right')
pydirectinput.moveRel(100, 0)
pydirectinput.mouseUp()
# --- Mouse Scrolling ---
# Scroll up
pydirectinput.scroll(10)
# Scroll down
pydirectinput.scroll(-10)

Keyboard Functions

import pydirectinput
import time
# --- Pressing Keys ---
# Press a single key
pydirectinput.press('a')
# Press a special key
pydirectinput.press('enter')
pydirectinput.press('esc')
pydirectinput.press('shift')
# --- Key Combinations (Hotkeys) ---
# To press a combination, you must press, release, and use keyDown/keyUp
# Example: Pressing Ctrl+C
pydirectinput.keyDown('ctrl')
pydirectinput.press('c')
pydirectinput.keyUp('ctrl')
# --- Typing Text ---
# Type a string of characters
pydirectinput.typewrite('Hello, world!')
# Typing with a pause between characters
pydirectinput.typewrite('This is a test.', interval=0.1)
# --- Checking Key State ---
# Note: pydirectinput doesn't have a built-in way to check if a key is currently
# pressed down. For that, you'd need a different library like `pynput`.
# However, you can use keyDown to simulate a held state.

Practical Example: A Simple Game Bot

Let's create a simple script that moves the mouse to the center of the screen, waits a second, and then types a message. This is a common starting point for automating tasks in games or applications.

import pydirectinput
import time
# A small safety feature to easily stop the script
# Move the mouse to the top-left corner of the screen to exit
def check_exit_condition():
    x, y = pydirectinput.position()
    if x == 0 and y == 0:
        print("Exit condition met (mouse in top-left corner). Stopping.")
        return True
    return False
print("Starting automation script. Move mouse to top-left corner to stop.")
try:
    # 1. Get screen size to find the center
    screen_width, screen_height = pydirectinput.size()
    center_x = screen_width // 2
    center_y = screen_height // 2
    print(f"Moving mouse to center: ({center_x}, {center_y})")
    # 2. Move the mouse to the center of the screen
    pydirectinput.moveTo(center_x, center_y)
    time.sleep(1) # Wait for 1 second
    # 3. Press 'enter' to open a chat window (common in many games)
    print("Pressing 'Enter' to open chat.")
    pydirectinput.press('enter')
    time.sleep(0.5)
    # 4. Type a message and press 'Enter' to send it
    print("Typing message...")
    pydirectinput.typewrite("Hello from Python!", interval=0.05)
    time.sleep(0.5)
    pydirectinput.press('enter')
    print("Script finished successfully.")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # This block will always run, ensuring we clean up
    print("Script ended.")

Advanced: Running in the Background with pynput

A major limitation of pydirectinput is that it cannot detect the current state of the keyboard or mouse (e.g., "Is the 'W' key currently pressed?"). It can only send input.

To build more complex bots (like a character that constantly holds 'W' to move forward), you need a second library: pynput.

如何用Python实现DirectInput?-图3
(图片来源网络,侵删)

pynput can listen for input events, while pydirectinput can send them. We'll use them together.

Installation:

pip install pynput

Example: A "Hold W to Move" Bot

This script will listen for the 'F1' key. When you press 'F1', it will start holding down the 'W' key. When you release 'F1', it will release 'W'.

from pynput import keyboard
import pydirectinput
import time
# --- The "bot" logic ---
is_bot_active = False
def on_press(key):
    """Called when a key is pressed."""
    global is_bot_active
    try:
        if key == keyboard.Key.f1:
            if not is_bot_active:
                print("Bot Activated! Holding 'W'.")
                is_bot_active = True
                pydirectinput.keyDown('w')
    except AttributeError:
        # Handle regular character keys if needed
        pass
def on_release(key):
    """Called when a key is released."""
    global is_bot_active
    try:
        if key == keyboard.Key.f1:
            if is_bot_active:
                print("Bot Deactivated. Releasing 'W'.")
                is_bot_active = False
                pydirectinput.keyUp('w')
        # Stop the listener if 'Esc' is pressed
        if key == keyboard.Key.esc:
            print('Exiting...')
            return False # Stop listener
    except AttributeError:
        pass
# --- Start the listener in a separate thread ---
# The 'with' statement ensures the listener is properly started and stopped
print("Starting listener. Press F1 to toggle bot, Esc to exit.")
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Important Considerations and Best Practices

  1. Admin Privileges: On Windows, you may need to run your Python script as an Administrator for pydirectinput to work correctly with some games (especially fullscreen ones).
  2. Focus: pydirectinput sends input to whichever window is currently active (has focus). Make sure your target application is the active window before running the script.
  3. Anti-Cheat Software: This is the most important point. Many online games have sophisticated anti-cheat systems (like Easy Anti-Cheat, BattlEye, VAC). Using pydirectinput for automation in these games will almost certainly get you banned. Use it responsibly, primarily for single-player games, testing your own applications, or harmless automation.
  4. Start Small: Always test your scripts in a safe environment (like Notepad or a simple drawing program) before using them in a complex game.
  5. Error Handling: Wrap your code in try...except blocks to handle potential errors gracefully (e.g., if the target window closes unexpectedly).
分享:
扫描分享到社交APP
上一篇
下一篇