文章目录
- 前言
- 项目结构
- 故事后续
前言
选完预三家,作者来到了橙华市。
众所周知啊,打架输了要掏一半的家产,所以宝可梦世界非常的危险。
为了安全考虑,作者打算在这里升个级。
项目结构
1,安装库。
pip install pynput
pip install pillow
2,base目录是一些通用的代码。
采样工具类。cai_yang.py
from PIL import Image
import random
# 目标图片
# 目标区域,左上XY右下XY,画图里面可以看到坐标
# 样本数量
def cai_yang(target: Image, rec: (int, int, int, int), count):
result = []
i = 1
while i <= count:
# 随机XY
x, y = random.randint(rec[0], rec[2]), random.randint(rec[1], rec[3])
result.append(((x, y), target.getpixel((x, y))))
i = i + 1
return result
# 对比
def is_same_img(img: Image, data):
for i in data:
if img.getpixel(i[0]) != i[1]:
return False
return True
# 用法示例
if __name__ == '__main__':
a = cai_yang(Image.open("a.png"), (1297, 262, 1488, 487), 8)
print(is_same_img(Image.open("b.png"), a))
键位设置。key_setting.py
import time
from pynput import keyboard as kb
########################
# 键位设置
UP = "w"
DOWN = "s"
LEFT = "a"
RIGHT = "d"
A = "j"
B = "k"
ACCELERATE = "u"
########################
# 一些按键方法
c = kb.Controller()
def press(key, t1=0.2, t2=0.1):
c.press(key)
time.sleep(t1)
c.release(key)
time.sleep(t2)
def run(key, t1=0.2, t2=0.1): # 主角跑步
c.press(B)
press(key, t1, t2)
c.release(B)
def walk(key): # 慢慢的走
c.release(ACCELERATE)
press(key, 0.2, 0.1)
c.press(ACCELERATE)
脚本启动器。script.py
from pynput import keyboard as kb
class Simple_Script():
def __init__(self, key, fun1=None, fun2=None):
self.key = key
self.state = False
self.listener = kb.Listener(on_press=self.__a(fun1, fun2))
def start(self):
self.listener.start()
def __a(self, fun1, fun2):
def on_press(key):
if key == self.key:
self.state = not self.state
if self.state:
print("启动", end="")
if fun1 != None:
fun1()
else:
print("暂停", end="")
if fun2 != None:
fun2()
return on_press
3,练级脚本。level.py
from PIL import ImageGrab
from base.cai_yang import *
from base.key_setting import *
from base.script import *
# 图片的采样数据
data_safe = cai_yang(Image.open("安全区.png"), (420, 335, 476, 384), 8)
data_pp = cai_yang(Image.open("没有PP.png"), (607, 827, 757, 914), 16)
# 战斗画面的关键像素点
pot_1 = ((1048, 490), (224, 192, 96))
if __name__ == '__main__':
a = Simple_Script(kb.Key.f12, lambda: c.press(ACCELERATE), lambda: c.release(ACCELERATE))
a.start()
state_can_attack = False
while True:
if a.state:
if is_same_img(ImageGrab.grab(), data_safe):
if state_can_attack: # 去草丛
run(RIGHT)
else: # 去治疗
walk(DOWN)
[walk(LEFT) for i in [1, 2, 3, 4]]
run(UP, 0.3)
[press(A) for i in [1, 2, 3, 4]]
[press(B) for i in [1, 2, 3, 4]]
run(DOWN, 0.3)
run(RIGHT, 0.3)
walk(LEFT)
run(UP)
state_can_attack = True
elif ImageGrab.grab().getpixel(pot_1[0]) == pot_1[1]:
if is_same_img(ImageGrab.grab(), data_pp):
state_can_attack = False
if state_can_attack: # 攻击
press(A)
else: # 逃跑
[press(B) for i in [1, 2, 3, 4]]
press(DOWN)
press(RIGHT)
press(A)
[press(B) for i in [1, 2, 3, 4]]
else: # 回安全区
run(LEFT)
4,需要的素材。
安全区的全屏截图。图中主角站的地方。范围可以选择精灵中心的标志。
PP不足的全屏截图。范围选PP两个字。
战斗画面的一个像素XY坐标和RGB颜色值。可以选择对面怪物的坐垫黄边。
故事后续
20级的猪。