原神风物之诗歌琴 Python

发布于 2022-04-11  792 次阅读


keyboard.py

实现模拟键盘输入

import pywinio
import atexit

KBC_KEY_CMD = 0x64
KBC_KEY_DATA = 0x60

g_winio = None

def get_winio():
    global g_winio
    if g_winio is None:
            g_winio = pywinio.WinIO()
            def __clear_winio():
                    global g_winio
                    g_winio = None
            atexit.register(__clear_winio)
    return g_winio

def wait_for_buffer_empty():
    winio = get_winio()
    dwRegVal = 0x02
    while (dwRegVal & 0x02):
            dwRegVal = winio.get_port_byte(KBC_KEY_CMD)

def key_down(scancode):
    winio = get_winio()
    wait_for_buffer_empty();
    winio.set_port_byte(KBC_KEY_CMD, 0xd2);
    wait_for_buffer_empty();
    winio.set_port_byte(KBC_KEY_DATA, scancode)

def key_up(scancode):
    winio = get_winio()
    wait_for_buffer_empty();
    winio.set_port_byte( KBC_KEY_CMD, 0xd2);
    wait_for_buffer_empty();
    winio.set_port_byte( KBC_KEY_DATA, scancode | 0x80);

def key_press(scancode):
    key_down( scancode )
    key_up( scancode )

main.py

import time
import keyboard as k

dic = {'Q': 0x10, 'W': 0x11, 'E': 0x12, 'R': 0x13, 'T': 0x14, 'Y': 0x15, 'U': 0x16,
       'A': 0x1e, 'S': 0x1f, 'D': 0x20, 'F': 0x21, 'G': 0x22, 'H': 0x23, 'J': 0x24,
       'Z': 0x2c, 'X': 0x2d, 'C': 0x2e, 'V': 0x2f, 'B': 0x30, 'N': 0x31, 'M': 0x32
       }

# 乐谱
# 前奏
begin = 'SMANSMAN'
# 主体
body = ' D    ASAD   ASASDN AN AN ASAM    D    ASAD   ASASDN AN AN ADSM   ' \
       'NAH HHGH HGHGHGD   NAH HHGHGJ JJHJHD' \
       '  DGDS DS DS DGDGDS DS DS  ASDNADS DSAAN    '
# 高潮
high = 'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'TE TE TETYET ' \
       'TE TE TETYET TTEWWQEWWQH    TTEWWQEWWQQH            ' \
       'HGH GHGHGHHGHGHGD   ' \
       'HGH GHGHGJ JJHJHD   ' \
       'DGDS DS DS DGDGDS DS DS ASDHQEW EWQH   ' \
       'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'TE TE TETYET ' \
       'TE TE TETYET TTEWWQEWWQH    TTEWWQEWWQQH            ' \
       'NADJ JJJHH    NADJ JJJHH    ' \
       'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'HJQWJQQ QJQWJQQ QWEWEWE EWE T E ' \
       'TE TE TETYET ' \
       'TE TE TETYET TTEWWQEWWQH    TTEWWQEWWQQH'

def play1():
    for i in range(5):
        for j in begin:
            k.key_press(dic[j])
            time.sleep(0.4)

def play2():
    for i in body:
        if i == ' ':
            time.sleep(0.35)
        else:
            k.key_press(dic[i])
            time.sleep(0.35)

def play3():
    for i in high:
        if i == ' ':
            time.sleep(0.3)
        else:
            k.key_press(dic[i])
            time.sleep(0.33)

if __name__ == '__main__':
    # 程序睡眠3s,期间手动切换到原神
    time.sleep(3)
    play1()
    play2()
    play3()
    # 模拟ESC键
    k.key_press(0x01)