Repository navigation
Expand file tree
/
Copy pathauto_queue.py
More file actions
431 lines (389 loc) · 18.8 KB
/
Copy pathauto_queue.py
File metadata and controls
431 lines (389 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
"""fn-auto-queue: readies up in the lobby and leaves the match when the
chosen teammate leaves.
Run: python auto_queue.py
Stop: F8 (or Ctrl+C in the console)
Test detection on screenshots of the game client area (or debug frames):
python auto_queue.py --test images/Ingame.png --region 640,336,1280,720
python auto_queue.py --test debug/20261126_201300 --target Ivakaa
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
import win32api
from PIL import Image
from fnq import ui
from fnq.debug import DebugRecorder
from fnq.ocr import OcrReader, find_line, normalize
from fnq.tracker import MatchTracker, Verdict
from fnq.vision import HAMBURGER, LOBBY_STATES, Detection, State, Vision
from fnq.window import GameWindow
ROOT = Path(__file__).parent
CONFIG_PATH = ROOT / "config.json"
DEBUG_DIR = ROOT / "debug"
DEFAULT_CONFIG = {
"target_player": "",
# Time between checks outside the fast in-match loop.
"check_interval_sec": 0.5,
# Time between checks in a match while the target is being watched.
"fast_check_interval_sec": 0.05,
# Re-read the squad list with OCR this often while the target is visible,
# to refresh the name templates.
"ocr_refresh_sec": 3.0,
# The target must be missing this many checks in a row ...
"missing_checks_to_leave": 5,
# ... and for at least this many seconds before the bot leaves.
"missing_seconds_to_leave": 1.5,
# Seconds needed instead when no other teammate is visible as reference
# (duo, or collapsed squad list) and only the own health bar is used.
"missing_seconds_hud_only": 4.0,
# Target eliminated (red name, reboot timer) but still in the match:
# true = leave anyway, false = stay until the target's row disappears.
"leave_when_target_dead": True,
# The target is watched only once the battle bus is seen (on the pregame
# island players load in and out of the squad list). If the bus is never
# seen, watching starts anyway this many seconds after the match loaded.
"bus_gate_timeout_sec": 300.0,
"name_match_threshold": 0.75,
"ready_click_cooldown_sec": 4.0,
# Minimum time between SPACE rounds on the placement / XP screen.
"skip_press_cooldown_sec": 1.5,
# Move the game window to the top-left corner of the screen when found.
"move_window_to_origin": True,
# Save screenshots of important events into debug/<run>/.
"debug_screenshots": True,
}
STOP_KEY = 0x77 # VK_F8
SKIP_PRESS_GAP_SEC = 0.3 # pause between SPACE presses in one round
JUMP_WORD = normalize("JUMP") # "Space TO JUMP" on the battle bus
log = ui.log
def stop_requested() -> bool:
return bool(win32api.GetAsyncKeyState(STOP_KEY) & 0x8000)
def sleep_checked(seconds: float) -> None:
end = time.time() + seconds
while True:
if stop_requested():
raise KeyboardInterrupt
left = end - time.time()
if left <= 0:
return
time.sleep(min(0.02, left))
# -- config -------------------------------------------------------------------
def load_config() -> dict:
cfg = dict(DEFAULT_CONFIG)
if CONFIG_PATH.exists():
try:
cfg.update(json.loads(CONFIG_PATH.read_text(encoding="utf-8")))
except (OSError, json.JSONDecodeError) as e:
log(f"config.json could not be read ({e}), using defaults.", "warn")
return cfg
def save_config(cfg: dict) -> None:
CONFIG_PATH.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8")
def make_tracker(cfg: dict, target: str) -> MatchTracker:
return MatchTracker(target, cfg["name_match_threshold"],
cfg["missing_checks_to_leave"], cfg["missing_seconds_to_leave"],
cfg["missing_seconds_hud_only"], cfg["leave_when_target_dead"])
# -- bot ----------------------------------------------------------------------
class Bot:
def __init__(self, cfg: dict, target: str) -> None:
self.cfg = cfg
self.target = target
self.ocr = OcrReader()
self.vision = Vision(self.ocr)
self.win = GameWindow()
self.tracker = make_tracker(cfg, target)
self.dbg = DebugRecorder(DEBUG_DIR, cfg["debug_screenshots"])
self.state: State | None = None
self.last_ready_click = 0.0
self.last_recap_click = 0.0
self.last_skip_press = 0.0
self.next_ocr_refresh = 0.0
self.warned_size = False
self.prepared_hwnd = None
self.status: ui.StatusBar | None = None
self.reset_bus_gate()
def reset_bus_gate(self) -> None:
self.bus_seen = False
self.match_seen_at: float | None = None
@property
def target_status(self) -> str:
if self.state == State.INGAME and not self.bus_seen:
return "waiting for bus"
return self.tracker.status
def bus_gate(self, frame: Image.Image, now: float) -> bool:
"""True once the battle bus was seen in this match. Before that the
target is not watched: on the pregame island players load in late and
drop out of the squad list. By the bus everyone is in. "Space TO JUMP"
marks the bus; the falling prompts ("ENTER FREE FALL", "TO DEPLOY")
also show on pregame launch pads, so they are not used."""
if self.bus_seen:
return True
if self.match_seen_at is None:
self.match_seen_at = now
lines = self.vision.bus_prompt(frame)
info = [f"bus prompt OCR: {[l.text for l in lines]}"]
reason = ""
if any(JUMP_WORD in l.norm for l in lines):
reason = "battle bus"
elif now - self.match_seen_at > self.cfg["bus_gate_timeout_sec"]:
reason = f"bus not seen in {self.cfg['bus_gate_timeout_sec']:g} s"
if not reason:
return False
log(f"{reason[0].upper() + reason[1:]} - watching target.", "ok")
self.dbg.save(frame, "battle_bus", info + [reason])
self.bus_seen = True
self.tracker.reset() # forget anything seen on the pregame island
return True
# -- helpers ----------------------------------------------------------
def prepare_window(self) -> None:
"""Once per game window (again after a game restart): focus, then move."""
if not self.win.find() or self.win.hwnd == self.prepared_hwnd:
return
if self.win.focus():
log("Fortnite window focused.", "ok")
else:
log("Could not focus the Fortnite window; will retry before each input.", "warn")
if self.cfg["move_window_to_origin"] and self.win.move_to_origin():
log("Game window moved to the top-left corner (0, 0).", "ok")
self.prepared_hwnd = self.win.hwnd
sleep_checked(0.5)
def set_state(self, state: State, frame: Image.Image | None, debug: list[str]) -> None:
if state == self.state:
return
log(state.value, "state")
self.dbg.save(frame, f"state_{state.name}", debug)
self.state = state
if state != State.INGAME and state not in (State.UNKNOWN,):
if self.tracker.armed:
log("Match over / back in lobby: target watch reset.", "info")
self.tracker.reset()
self.reset_bus_gate()
self.dbg.clear_ring()
# -- main loop --------------------------------------------------------
def run(self) -> None:
with ui.StatusBar(self.target) as status:
self.status = status
while True:
t0 = time.perf_counter()
self.prepare_window()
frame = self.win.capture()
fast = self.step(frame)
status.update(state=self.state or State.UNKNOWN,
target_status=self.target_status,
check_ms=(time.perf_counter() - t0) * 1000)
sleep_checked(self.cfg["fast_check_interval_sec"] if fast
else self.cfg["check_interval_sec"])
def step(self, frame: Image.Image | None) -> bool:
"""One check. Returns True when the fast in-match interval applies."""
if frame is None:
self.set_state(State.NO_WINDOW, None, [])
return False
if not self.warned_size and abs(frame.width / frame.height - 16 / 9) > 0.02:
log(f"Window is {frame.width}x{frame.height}, not 16:9; detection may be inaccurate.", "warn")
self.warned_size = True
now = time.time()
# Fast path: in a match with the target armed. Pixel template only
# (about 15 ms); OCR runs only when the template does not match.
if self.state == State.INGAME and self.tracker.armed:
if self.tracker.quick_present(frame) and now < self.next_ocr_refresh:
return True
lines = self.vision.read_squad(frame, self.tracker.squad_read_done)
v = self.track(frame, lines, now)
self.next_ocr_refresh = now + self.cfg["ocr_refresh_sec"]
self.handle_verdict(frame, v, [f"squad OCR: {[l.text for l in lines]}"])
if v.event != "hud_hidden":
return True
# HUD not readable: maybe the match ended. Fall through to full detection.
det = self.vision.detect(frame, self.tracker.squad_read_done)
self.set_state(det.state, frame, det.debug)
if det.state == State.LOBBY_NOT_READY:
if time.time() - self.last_ready_click >= self.cfg["ready_click_cooldown_sec"]:
log("Clicking READY", "action")
self.dbg.save(frame, "click_ready", det.debug + [f"click {det.ready_click}"])
self.win.click(*det.ready_click)
self.last_ready_click = time.time()
elif det.state == State.ERROR_DIALOG:
if time.time() - self.last_recap_click >= self.cfg["ready_click_cooldown_sec"]:
log("Error dialog - clicking CONTINUE", "action")
self.dbg.save(frame, "click_error_continue", det.debug + [f"click {det.continue_click}"])
self.win.click(*det.continue_click)
self.last_recap_click = time.time()
elif det.state == State.PLACEMENT:
if time.time() - self.last_skip_press >= self.cfg["skip_press_cooldown_sec"]:
log(f"Placement screen - pressing SPACE x{det.skip_presses}", "action")
self.dbg.save(frame, "press_skip_placement", det.debug)
for i in range(det.skip_presses):
if i:
sleep_checked(SKIP_PRESS_GAP_SEC)
self.win.press("space")
self.last_skip_press = time.time()
elif det.state == State.REWARD:
if time.time() - self.last_recap_click >= self.cfg["ready_click_cooldown_sec"]:
log("Reward screen - clicking CLAIM", "action")
self.dbg.save(frame, "click_claim", det.debug + [f"click {det.claim_click}"])
self.win.click(*det.claim_click)
self.last_recap_click = time.time()
elif det.state == State.MATCH_RECAP:
if time.time() - self.last_recap_click >= self.cfg["ready_click_cooldown_sec"]:
log("Match recap - clicking Return to lobby", "action")
self.dbg.save(frame, "click_recap_return", det.debug + [f"click {det.recap_click}"])
self.win.click(*det.recap_click)
self.last_recap_click = time.time()
elif det.state == State.INGAME:
if not self.bus_gate(frame, now):
return False
v = self.track(frame, det.squad_lines, now)
self.next_ocr_refresh = now + self.cfg["ocr_refresh_sec"]
self.handle_verdict(frame, v, det.debug)
return self.tracker.armed
return False
def track(self, frame: Image.Image, lines, now: float) -> Verdict:
return self.tracker.update(frame, lines, now,
own_hud=self.vision.own_hud_visible(frame),
find_elsewhere=lambda: self.vision.read_full(frame))
def handle_verdict(self, frame: Image.Image, v: Verdict, debug: list[str]) -> None:
info = debug + v.info
self.dbg.remember(frame, info)
if v.event == "armed":
log(f"Target [bold bright_yellow]{self.target}[/] spotted in squad list - watching.", "ok")
self.dbg.save(frame, "armed", info)
elif v.event == "ocr_miss_pixel_present":
self.dbg.save(frame, "ocr_miss_pixel_present", info, min_interval=5.0)
elif v.event == "hud_hidden":
self.dbg.save(frame, "hud_hidden", info, min_interval=10.0)
elif v.event == "target_elsewhere":
self.dbg.save(frame, "target_elsewhere", info, min_interval=10.0)
elif v.event in ("target_row_present", "target_row_dead"):
# Name unreadable, but the target's row (portrait) is still there.
self.dbg.save(frame, v.event, info, min_interval=10.0)
elif v.counted_missing:
# Log only the first miss; the status bar shows the running count.
if self.tracker.missing == 1:
log("Target not visible - confirming...", "warn")
self.dbg.save(frame, v.event, info)
if v.leave:
log(f"Target [bold bright_yellow]{self.target}[/] LEFT - leaving the match!", "alert")
self.dbg.dump_ring("before_leave")
if self.leave_match():
if self.status:
self.status.update(leaves=self.status.leaves + 1)
else:
self.dbg.save(self.win.capture(), "leave_failed", [])
self.tracker.reset()
def leave_match(self, timeout: float = 12.0) -> bool:
"""ESC -> hamburger -> Return to lobby, polling the screen instead of
fixed waits so each step fires as soon as the UI is ready."""
log("Pressing ESC", "action")
if not self.win.press("esc"):
log("Could not focus the game window; leave aborted.", "alert")
return False
esc_at, hamburger_at = time.time(), 0.0
end = time.time() + timeout
while time.time() < end:
frame = self.win.capture()
if frame is None:
return False
lines = self.vision.menu_lines(frame)
info = [f"menu OCR: {[l.text for l in lines]}"]
btn = find_line(lines, "Return to lobby")
now = time.time()
if btn:
cx, cy = btn.center
log("Clicking Return to lobby", "action")
self.dbg.save(frame, "menu_return_to_lobby", info + [f"click ({cx:.0f},{cy:.0f})"])
self.win.click(round(cx), round(cy))
return True
if self.vision.menu_open(frame, lines):
if now - hamburger_at > 1.5:
log("Clicking hamburger menu", "action")
self.dbg.save(frame, "menu_hamburger", info)
self.win.click(*self.vision.point(frame, HAMBURGER))
hamburger_at = now
elif now - esc_at > 1.5:
log("Menu not visible - pressing ESC again", "warn")
self.dbg.save(frame, "menu_not_visible", info)
self.win.press("esc")
esc_at = now
sleep_checked(0.05)
log("Return to lobby not found.", "alert")
return False
def run(cfg: dict) -> None:
ui.banner()
target = ui.ask_target(cfg.get("target_player", "").strip())
cfg["target_player"] = target
save_config(cfg)
bot = Bot(cfg, target)
ui.info_panel([
("Target", f"[bold bright_yellow]{target}[/]"),
("OCR language", bot.ocr.language),
("Leave after", f"{cfg['missing_checks_to_leave']} checks and "
f"{cfg['missing_seconds_to_leave']:g} s missing"),
("Target eliminated", "leave" if cfg["leave_when_target_dead"]
else "stay until the target leaves"),
("Debug", str(bot.dbg.dir) if bot.dbg.enabled else "off"),
("Stop", "F8 or Ctrl+C"),
])
bot.run()
# -- offline test -------------------------------------------------------------
def collect_images(paths: list[str]) -> list[Path]:
out: list[Path] = []
for p in map(Path, paths):
out += sorted(p.glob("*.png")) if p.is_dir() else [p]
return out
def test_images(paths: list[str], region: str | None, target: str | None, cfg: dict) -> None:
# OCR text can hold characters the console code page cannot print.
sys.stdout.reconfigure(errors="replace")
vision = Vision(OcrReader())
tracker = make_tracker(cfg, target) if target else None
now = 0.0
for path in collect_images(paths):
frame = Image.open(path).convert("RGB")
if region:
x, y, w, h = (int(v) for v in region.split(","))
frame = frame.crop((x, y, x + w, y + h))
det = vision.detect(frame, tracker.squad_read_done if tracker else None)
print(f"{path}: {det.state.value}")
for d in det.debug:
print(" ", d)
if det.ready_click:
print(" READY click:", det.ready_click)
if det.recap_click:
print(" Return to lobby click:", det.recap_click)
if det.continue_click:
print(" CONTINUE click:", det.continue_click)
if det.claim_click:
print(" CLAIM click:", det.claim_click)
if det.state == State.INGAME:
prompt = [l.text for l in vision.bus_prompt(frame)]
print(f" bus prompt: {prompt} -> "
f"bus={any(JUMP_WORD in normalize(t) for t in prompt)}")
if tracker and det.state == State.INGAME:
v = tracker.update(frame, det.squad_lines, now,
own_hud=vision.own_hud_visible(frame),
find_elsewhere=lambda: vision.read_full(frame))
print(f" tracker: event={v.event or '-'} leave={v.leave}")
for i in v.info:
print(" ", i)
lines = vision.menu_lines(frame)
print(" menu open:", vision.menu_open(frame, lines),
"| Return to lobby:", bool(find_line(lines, "Return to lobby")))
now += cfg["check_interval_sec"]
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--test", nargs="+", metavar="PATH", help="test detection on images or a debug folder")
ap.add_argument("--region", help="x,y,w,h: game client area inside the image")
ap.add_argument("--target", help="target name for --test (simulates the tracker)")
args = ap.parse_args()
cfg = load_config()
if args.test:
test_images(args.test, args.region, args.target, cfg)
return
try:
run(cfg)
except KeyboardInterrupt:
log("Stopped.", "info")
sys.exit(0)
if __name__ == "__main__":
main()