kotonebot 0.1.0__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kotonebot/backend/loop.py CHANGED
@@ -1,277 +1,284 @@
1
- import time
2
- from functools import lru_cache, partial
3
- from typing import Callable, Any, overload, Literal, Generic, TypeVar, cast, get_args, get_origin
4
-
5
- from cv2.typing import MatLike
6
-
7
- from kotonebot.util import Interval
8
- from kotonebot import device, image, ocr
9
- from kotonebot.backend.core import Image
10
- from kotonebot.backend.ocr import TextComparator
11
- from kotonebot.client.protocol import ClickableObjectProtocol
12
-
13
-
14
- class LoopAction:
15
- def __init__(self, loop: 'Loop', func: Callable[[], ClickableObjectProtocol | None]):
16
- self.loop = loop
17
- self.func = func
18
- self.result: ClickableObjectProtocol | None = None
19
-
20
- @property
21
- def found(self):
22
- """
23
- 是否找到结果。若父 Loop 未在运行中,则返回 False。
24
- """
25
- if not self.loop.running:
26
- return False
27
- return bool(self.result)
28
-
29
- def __bool__(self):
30
- return self.found
31
-
32
- def reset(self):
33
- """
34
- 重置 LoopAction,以复用此对象。
35
- """
36
- self.result = None
37
-
38
- def do(self):
39
- """
40
- 执行 LoopAction。
41
- :return: 执行结果。
42
- """
43
- if not self.loop.running:
44
- return
45
- if self.loop.found_anything:
46
- # 本轮循环已执行任意操作,因此不需要再继续检测
47
- return
48
- self.result = self.func()
49
- if self.result:
50
- self.loop.found_anything = True
51
-
52
- def click(self, *, at: tuple[int, int] | None = None):
53
- """
54
- 点击寻找结果。若结果为空,会跳过执行。
55
-
56
- :return:
57
- """
58
- if self.result:
59
- if at is not None:
60
- device.click(*at)
61
- else:
62
- device.click(self.result)
63
-
64
- def call(self, func: Callable[[ClickableObjectProtocol], Any]):
65
- pass
66
-
67
-
68
- class Loop:
69
- def __init__(
70
- self,
71
- *,
72
- timeout: float = 300,
73
- interval: float = 0.3,
74
- auto_screenshot: bool = True
75
- ):
76
- self.running = True
77
- self.found_anything = False
78
- self.auto_screenshot = auto_screenshot
79
- """
80
- 是否在每次循环开始时(Loop.tick() 被调用时)截图。
81
- """
82
- self.__last_loop: float = -1
83
- self.__interval = Interval(interval)
84
- self.screenshot: MatLike | None = None
85
- """上次截图时的图像数据。"""
86
-
87
- def __iter__(self):
88
- self.__interval.reset()
89
- return self
90
-
91
- def __next__(self):
92
- if not self.running:
93
- raise StopIteration
94
- self.found_anything = False
95
- self.__last_loop = time.time()
96
- return self.tick()
97
-
98
- def tick(self):
99
- self.__interval.wait()
100
- if self.auto_screenshot:
101
- self.screenshot = device.screenshot()
102
- self.__last_loop = time.time()
103
- self.found_anything = False
104
- return self
105
-
106
- def exit(self):
107
- """
108
- 结束循环。
109
- """
110
- self.running = False
111
-
112
- @overload
113
- def when(self, condition: Image) -> LoopAction:
114
- ...
115
-
116
- @overload
117
- def when(self, condition: TextComparator) -> LoopAction:
118
- ...
119
-
120
- def when(self, condition: Any):
121
- """
122
- 判断某个条件是否成立。
123
-
124
- :param condition:
125
- :return:
126
- """
127
- if isinstance(condition, Image):
128
- func = partial(image.find, condition)
129
- elif isinstance(condition, TextComparator):
130
- func = partial(ocr.find, condition)
131
- else:
132
- raise ValueError('Invalid condition type.')
133
- la = LoopAction(self, func)
134
- la.reset()
135
- la.do()
136
- return la
137
-
138
- def until(self, condition: Any):
139
- """
140
- 当满足指定条件时,结束循环。
141
-
142
- 等价于 ``loop.when(...).call(lambda _: loop.exit())``
143
- """
144
- return self.when(condition).call(lambda _: self.exit())
145
-
146
- def click_if(self, condition: Any, *, at: tuple[int, int] | None = None):
147
- """
148
- 检测指定对象是否出现,若出现,点击该对象或指定位置。
149
-
150
- ``click_if()`` 等价于 ``loop.when(...).click(...)``。
151
-
152
- :param condition: 检测目标。
153
- :param at: 点击位置。若为 None,表示点击找到的目标。
154
- """
155
- return self.when(condition).click(at=at)
156
-
157
- StateType = TypeVar('StateType')
158
- class StatedLoop(Loop, Generic[StateType]):
159
- def __init__(
160
- self,
161
- states: list[Any] | None = None,
162
- initial_state: StateType | None = None,
163
- *,
164
- timeout: float = 300,
165
- interval: float = 0.3,
166
- auto_screenshot: bool = True
167
- ):
168
- self.__tmp_states = states
169
- self.__tmp_initial_state = initial_state
170
- self.state: StateType
171
- super().__init__(timeout=timeout, interval=interval, auto_screenshot=auto_screenshot)
172
-
173
- def __iter__(self):
174
- # __retrive_state_values() 只能在非 __init__ 中调用
175
- self.__retrive_state_values()
176
- return super().__iter__()
177
-
178
- def __retrive_state_values(self):
179
- # HACK: __orig_class__ 是 undocumented 属性
180
- if not hasattr(self, '__orig_class__'):
181
- # 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
182
- if self.state is None:
183
- raise ValueError('Either specify `states` or use StatedLoop[Literal[...]] syntax.')
184
- else:
185
- generic_type_args = get_args(self.__orig_class__) # type: ignore
186
- if len(generic_type_args) != 1:
187
- raise ValueError('StatedLoop must have exactly one generic type argument.')
188
- state_values = get_args(generic_type_args[0])
189
- if not state_values:
190
- raise ValueError('StatedLoop must have at least one state value.')
191
- self.states = cast(tuple[StateType, ...], state_values)
192
- self.state = self.__tmp_initial_state or self.states[0]
193
- return state_values
194
-
195
-
196
- def StatedLoop2(states: StateType) -> StatedLoop[StateType]:
197
- state_values = get_args(states)
198
- return cast(StatedLoop[StateType], Loop())
199
-
200
- if __name__ == '__main__':
201
- from kotonebot.kaa.tasks import R
202
- from kotonebot.backend.ocr import contains
203
- from kotonebot.backend.context import manual_context, init_context
204
-
205
- # T = TypeVar('T')
206
- # class Foo(Generic[T]):
207
- # def get_literal_params(self) -> list | None:
208
- # """
209
- # 尝试获取泛型参数 T (如果它是 Literal 类型) 的参数列表。
210
- # """
211
- # # self.__orig_class__ 会是 Foo 的具体参数化类型,
212
- # # 例如 Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]
213
- # if not hasattr(self, '__orig_class__'):
214
- # # 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
215
- # return None
216
- #
217
- # # generic_type_args 是传递给 Foo 的类型参数元组
218
- # # 例如 (Literal['p0', 'p1', 'p2', 'p3', 'ap'],)
219
- # generic_type_args = get_args(self.__orig_class__)
220
- #
221
- # if not generic_type_args:
222
- # # Foo 没有类型参数
223
- # return None
224
- #
225
- # # T_type Foo 的第一个类型参数
226
- # # 例如 Literal['p0', 'p1', 'p2', 'p3', 'ap']
227
- # t_type = generic_type_args[0]
228
- #
229
- # # 检查 T_type 是否是 Literal 类型
230
- # if get_origin(t_type) is Literal:
231
- # # literal_args 是 Literal 类型的参数元组
232
- # # 例如 ('p0', 'p1', 'p2', 'p3', 'ap')
233
- # literal_args = get_args(t_type)
234
- # return list(literal_args)
235
- # else:
236
- # # T 不是 Literal 类型
237
- # return None
238
- # f = Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
239
- # values = f.get_literal_params()
240
- # 1
241
-
242
- from typing_extensions import reveal_type
243
- slp = StatedLoop[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
244
- for l in slp:
245
- reveal_type(l.states)
246
-
247
- # init_context()
248
- # manual_context().begin()
249
- # for l in Loop():
250
- # l.when(R.Produce.ButtonUse).click()
251
- # l.when(R.Produce.ButtonRefillAP).click()
252
- # l.when(contains("123")).click()
253
- # l.click_if(contains("!23"), at=(1, 2))
254
-
255
- # State = Literal['p0', 'p1', 'p2', 'p3', 'ap']
256
- # for sl in StatedLoop[State]():
257
- # match sl.state:
258
- # case 'p0':
259
- # sl.click_if(R.Produce.ButtonProduce)
260
- # sl.click_if(contains('master'))
261
- # sl.when(R.Produce.ButtonPIdolOverview).goto('p1')
262
- # # AP 不足
263
- # sl.when(R.Produce.TextAPInsufficient).goto('ap')
264
- # case 'ap':
265
- # pass
266
- # # p1: 选择偶像
267
- # case 'p1':
268
- # sl.call(lambda _: select_idol(idol_skin_id), once=True)
269
- # sl.when(R.Produce.TextAnotherIdolAvailableDialog).call(dialog.no)
270
- # sl.click_if(R.Common.ButtonNextNoIcon)
271
- # sl.until(R.Produce.TextStepIndicator2).goto('p2')
272
- # case 'p2':
273
- # sl.when(contains("123")).click()
274
- # case 'p3':
275
- # sl.click_if(contains("!23"), at=(1, 2))
276
- # case _:
1
+ import time
2
+ from functools import lru_cache, partial
3
+ from typing import Callable, Any, overload, Literal, Generic, TypeVar, cast, get_args, get_origin
4
+
5
+ from cv2.typing import MatLike
6
+
7
+ from kotonebot.util import Interval
8
+ from kotonebot import device, image, ocr
9
+ from kotonebot.backend.core import Image
10
+ from kotonebot.backend.ocr import TextComparator
11
+ from kotonebot.client.protocol import ClickableObjectProtocol
12
+
13
+
14
+ class LoopAction:
15
+ def __init__(self, loop: 'Loop', func: Callable[[], ClickableObjectProtocol | None]):
16
+ self.loop = loop
17
+ self.func = func
18
+ self.result: ClickableObjectProtocol | None = None
19
+
20
+ @property
21
+ def found(self):
22
+ """
23
+ 是否找到结果。若父 Loop 未在运行中,则返回 False。
24
+ """
25
+ if not self.loop.running:
26
+ return False
27
+ return bool(self.result)
28
+
29
+ def __bool__(self):
30
+ return self.found
31
+
32
+ def reset(self):
33
+ """
34
+ 重置 LoopAction,以复用此对象。
35
+ """
36
+ self.result = None
37
+
38
+ def do(self):
39
+ """
40
+ 执行 LoopAction。
41
+ :return: 执行结果。
42
+ """
43
+ if not self.loop.running:
44
+ return
45
+ if self.loop.found_anything:
46
+ # 本轮循环已执行任意操作,因此不需要再继续检测
47
+ return
48
+ self.result = self.func()
49
+ if self.result:
50
+ self.loop.found_anything = True
51
+
52
+ def click(self, *, at: tuple[int, int] | None = None):
53
+ """
54
+ 点击寻找结果。若结果为空,会跳过执行。
55
+
56
+ :return:
57
+ """
58
+ if self.result:
59
+ if at is not None:
60
+ device.click(*at)
61
+ else:
62
+ device.click(self.result)
63
+
64
+ def call(self, func: Callable[[ClickableObjectProtocol], Any]):
65
+ pass
66
+
67
+
68
+ class Loop:
69
+ def __init__(
70
+ self,
71
+ *,
72
+ timeout: float = 300,
73
+ interval: float = 0.3,
74
+ auto_screenshot: bool = True,
75
+ skip_first_wait: bool = True
76
+ ):
77
+ self.running = True
78
+ self.found_anything = False
79
+ self.auto_screenshot = auto_screenshot
80
+ """
81
+ 是否在每次循环开始时(Loop.tick() 被调用时)截图。
82
+ """
83
+ self.__last_loop: float = -1
84
+ self.__interval = Interval(interval)
85
+ self.screenshot: MatLike | None = None
86
+ """上次截图时的图像数据。"""
87
+ self.__skip_first_wait = skip_first_wait
88
+ self.__is_first_tick = True
89
+
90
+ def __iter__(self):
91
+ self.__interval.reset()
92
+ self.__is_first_tick = True
93
+ return self
94
+
95
+ def __next__(self):
96
+ if not self.running:
97
+ raise StopIteration
98
+ self.found_anything = False
99
+ self.__last_loop = time.time()
100
+ return self.tick()
101
+
102
+ def tick(self):
103
+ if not (self.__is_first_tick and self.__skip_first_wait):
104
+ self.__interval.wait()
105
+ self.__is_first_tick = False
106
+
107
+ if self.auto_screenshot:
108
+ self.screenshot = device.screenshot()
109
+ self.__last_loop = time.time()
110
+ self.found_anything = False
111
+ return self
112
+
113
+ def exit(self):
114
+ """
115
+ 结束循环。
116
+ """
117
+ self.running = False
118
+
119
+ @overload
120
+ def when(self, condition: Image) -> LoopAction:
121
+ ...
122
+
123
+ @overload
124
+ def when(self, condition: TextComparator) -> LoopAction:
125
+ ...
126
+
127
+ def when(self, condition: Any):
128
+ """
129
+ 判断某个条件是否成立。
130
+
131
+ :param condition:
132
+ :return:
133
+ """
134
+ if isinstance(condition, Image):
135
+ func = partial(image.find, condition)
136
+ elif isinstance(condition, TextComparator):
137
+ func = partial(ocr.find, condition)
138
+ else:
139
+ raise ValueError('Invalid condition type.')
140
+ la = LoopAction(self, func)
141
+ la.reset()
142
+ la.do()
143
+ return la
144
+
145
+ def until(self, condition: Any):
146
+ """
147
+ 当满足指定条件时,结束循环。
148
+
149
+ 等价于 ``loop.when(...).call(lambda _: loop.exit())``
150
+ """
151
+ return self.when(condition).call(lambda _: self.exit())
152
+
153
+ def click_if(self, condition: Any, *, at: tuple[int, int] | None = None):
154
+ """
155
+ 检测指定对象是否出现,若出现,点击该对象或指定位置。
156
+
157
+ ``click_if()`` 等价于 ``loop.when(...).click(...)``。
158
+
159
+ :param condition: 检测目标。
160
+ :param at: 点击位置。若为 None,表示点击找到的目标。
161
+ """
162
+ return self.when(condition).click(at=at)
163
+
164
+ StateType = TypeVar('StateType')
165
+ class StatedLoop(Loop, Generic[StateType]):
166
+ def __init__(
167
+ self,
168
+ states: list[Any] | None = None,
169
+ initial_state: StateType | None = None,
170
+ *,
171
+ timeout: float = 300,
172
+ interval: float = 0.3,
173
+ auto_screenshot: bool = True
174
+ ):
175
+ self.__tmp_states = states
176
+ self.__tmp_initial_state = initial_state
177
+ self.state: StateType
178
+ super().__init__(timeout=timeout, interval=interval, auto_screenshot=auto_screenshot)
179
+
180
+ def __iter__(self):
181
+ # __retrive_state_values() 只能在非 __init__ 中调用
182
+ self.__retrive_state_values()
183
+ return super().__iter__()
184
+
185
+ def __retrive_state_values(self):
186
+ # HACK: __orig_class__ 是 undocumented 属性
187
+ if not hasattr(self, '__orig_class__'):
188
+ # 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
189
+ if self.state is None:
190
+ raise ValueError('Either specify `states` or use StatedLoop[Literal[...]] syntax.')
191
+ else:
192
+ generic_type_args = get_args(self.__orig_class__) # type: ignore
193
+ if len(generic_type_args) != 1:
194
+ raise ValueError('StatedLoop must have exactly one generic type argument.')
195
+ state_values = get_args(generic_type_args[0])
196
+ if not state_values:
197
+ raise ValueError('StatedLoop must have at least one state value.')
198
+ self.states = cast(tuple[StateType, ...], state_values)
199
+ self.state = self.__tmp_initial_state or self.states[0]
200
+ return state_values
201
+
202
+
203
+ def StatedLoop2(states: StateType) -> StatedLoop[StateType]:
204
+ state_values = get_args(states)
205
+ return cast(StatedLoop[StateType], Loop())
206
+
207
+ if __name__ == '__main__':
208
+ from kotonebot.kaa.tasks import R
209
+ from kotonebot.backend.ocr import contains
210
+ from kotonebot.backend.context import manual_context, init_context
211
+
212
+ # T = TypeVar('T')
213
+ # class Foo(Generic[T]):
214
+ # def get_literal_params(self) -> list | None:
215
+ # """
216
+ # 尝试获取泛型参数 T (如果它是 Literal 类型) 的参数列表。
217
+ # """
218
+ # # self.__orig_class__ 会是 Foo 的具体参数化类型,
219
+ # # 例如 Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]
220
+ # if not hasattr(self, '__orig_class__'):
221
+ # # 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
222
+ # return None
223
+ #
224
+ # # generic_type_args 是传递给 Foo 的类型参数元组
225
+ # # 例如 (Literal['p0', 'p1', 'p2', 'p3', 'ap'],)
226
+ # generic_type_args = get_args(self.__orig_class__)
227
+ #
228
+ # if not generic_type_args:
229
+ # # Foo 没有类型参数
230
+ # return None
231
+ #
232
+ # # T_type Foo 的第一个类型参数
233
+ # # 例如 Literal['p0', 'p1', 'p2', 'p3', 'ap']
234
+ # t_type = generic_type_args[0]
235
+ #
236
+ # # 检查 T_type 是否是 Literal 类型
237
+ # if get_origin(t_type) is Literal:
238
+ # # literal_args Literal 类型的参数元组
239
+ # # 例如 ('p0', 'p1', 'p2', 'p3', 'ap')
240
+ # literal_args = get_args(t_type)
241
+ # return list(literal_args)
242
+ # else:
243
+ # # T 不是 Literal 类型
244
+ # return None
245
+ # f = Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
246
+ # values = f.get_literal_params()
247
+ # 1
248
+
249
+ from typing_extensions import reveal_type
250
+ slp = StatedLoop[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
251
+ for l in slp:
252
+ reveal_type(l.states)
253
+
254
+ # init_context()
255
+ # manual_context().begin()
256
+ # for l in Loop():
257
+ # l.when(R.Produce.ButtonUse).click()
258
+ # l.when(R.Produce.ButtonRefillAP).click()
259
+ # l.when(contains("123")).click()
260
+ # l.click_if(contains("!23"), at=(1, 2))
261
+
262
+ # State = Literal['p0', 'p1', 'p2', 'p3', 'ap']
263
+ # for sl in StatedLoop[State]():
264
+ # match sl.state:
265
+ # case 'p0':
266
+ # sl.click_if(R.Produce.ButtonProduce)
267
+ # sl.click_if(contains('master'))
268
+ # sl.when(R.Produce.ButtonPIdolOverview).goto('p1')
269
+ # # AP 不足
270
+ # sl.when(R.Produce.TextAPInsufficient).goto('ap')
271
+ # case 'ap':
272
+ # pass
273
+ # # p1: 选择偶像
274
+ # case 'p1':
275
+ # sl.call(lambda _: select_idol(idol_skin_id), once=True)
276
+ # sl.when(R.Produce.TextAnotherIdolAvailableDialog).call(dialog.no)
277
+ # sl.click_if(R.Common.ButtonNextNoIcon)
278
+ # sl.until(R.Produce.TextStepIndicator2).goto('p2')
279
+ # case 'p2':
280
+ # sl.when(contains("123")).click()
281
+ # case 'p3':
282
+ # sl.click_if(contains("!23"), at=(1, 2))
283
+ # case _:
277
284
  # assert_never(sl.state)
@@ -292,7 +292,10 @@ class Device:
292
292
 
293
293
  def swipe_scaled(self, x1: float, y1: float, x2: float, y2: float, duration: float|None = None) -> None:
294
294
  """
295
- 滑动屏幕,参数为屏幕坐标的百分比
295
+ 滑动屏幕,参数为屏幕坐标的百分比。
296
+
297
+ 如果设置了 `self.target_resolution`,则参数为逻辑坐标百分比。
298
+ 否则为真实坐标百分比。
296
299
 
297
300
  :param x1: 起始点 x 坐标百分比。范围 [0, 1]
298
301
  :param y1: 起始点 y 坐标百分比。范围 [0, 1]
@@ -300,7 +303,7 @@ class Device:
300
303
  :param y2: 结束点 y 坐标百分比。范围 [0, 1]
301
304
  :param duration: 滑动持续时间,单位秒。None 表示使用默认值。
302
305
  """
303
- w, h = self.screen_size
306
+ w, h = self.target_resolution or self.screen_size
304
307
  self.swipe(int(w * x1), int(h * y1), int(w * x2), int(h * y2), duration)
305
308
 
306
309
  def screenshot(self) -> MatLike:
@@ -334,7 +337,7 @@ class Device:
334
337
  @property
335
338
  def screen_size(self) -> tuple[int, int]:
336
339
  """
337
- 屏幕尺寸。格式为 `(width, height)`。
340
+ 真实屏幕尺寸。格式为 `(width, height)`。
338
341
 
339
342
  **注意**: 此属性返回的分辨率会随设备方向变化。
340
343
  如果 `self.orientation` 为 `landscape`,则返回的分辨率是横屏下的分辨率,