import json
import os
import time
import requests
import websocket
from colorama import init, Fore, Style
# Инициализируем colorama для корректной работы в Windows 7
# autoreset=True автоматически сбрасывает цвет после каждой строки
init(autoreset=True)
# --- ОФОРМЛЕНИЕ ФИШЕК И КЛЕТОК ---
# Fore.RED + Style.BRIGHT = Ярко-красный
# Fore.BLUE + Style.BRIGHT = Ярко-синий (или Fore.CYAN для более светлого)
RED_X = Fore.RED + Style.BRIGHT + "X" + Style.RESET_ALL
BLUE_X = Fore.CYAN + Style.BRIGHT + "X" + Style.RESET_ALL
RED_K = Fore.RED + Style.BRIGHT + "K" + Style.RESET_ALL
BLUE_K = Fore.CYAN + Style.BRIGHT + "K" + Style.RESET_ALL
EMPTY = Fore.LIGHTBLACK_EX + "·" + Style.RESET_ALL
def eval_js_in_opera(js_code):
"""Отправляет JavaScript-код в открытую вкладку Opera GX"""
try:
res = requests.get("http://127.0.0.1:9222/json").json()
target_tab = None
for tab in res:
if tab.get("type") == "page" and "checkers" in tab.get("url", ""):
target_tab = tab
break
if not target_tab:
for tab in res:
if tab.get("type") == "page":
target_tab = tab
break
if not target_tab:
return None
ws_url = target_tab["webSocketDebuggerUrl"]
ws = websocket.create_connection(ws_url)
payload = {
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": js_code,
"returnByValue": True
}
}
ws.send(json.dumps(payload))
response = json.loads(ws.recv())
ws.close()
return response.get("result", {}).get("result", {}).get("value")
except Exception:
return None
def clear_screen():
"""Очистка консоли Windows"""
os.system('cls')
def render_board(board):
"""Отрисовка красивой доски в консоли с помощью Colorama"""
clear_screen()
print(" A B C D E F G H")
print(" ┌─────────────────┐")
for r_idx, row in enumerate(board):
row_str = f" {r_idx + 1} │ "
for c_idx, cell in enumerate(row):
if cell == 1:
symbol = RED_X
elif cell == 2:
symbol = BLUE_X
elif cell == 3:
symbol = RED_K
elif cell == 4:
symbol = BLUE_K
elif cell == 0:
symbol = EMPTY
else:
symbol = " "
row_str += symbol + " "
row_str += "│"
print(row_str)
print(" └─────────────────┘")
print("\n [+] Отслеживание доски активно...")
# --- ГЛАВНЫЙ ЦИКЛ ---
last_board = None
try:
while True:
board = eval_js_in_opera("checkers.engine.getField();")
if board:
# Обновляем экран только при изменении состояния
if board != last_board:
render_board(board)
last_board = board
else:
clear_screen()
print("Ожидание подключения к Opera GX...")
print("Убедитесь, что страница с шашками открыта.")
time.sleep(1)
except KeyboardInterrupt:
print("\nСкрипт остановлен.")