scratch-next 3.0.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.
- scratch_next/__init__.py +43 -0
- scratch_next/ai_integrations.py +124 -0
- scratch_next/analytics_encoding.py +167 -0
- scratch_next/ast_tools.py +93 -0
- scratch_next/async_engine.py +76 -0
- scratch_next/cache_http.py +135 -0
- scratch_next/cli.py +51 -0
- scratch_next/cloud.py +228 -0
- scratch_next/exceptions.py +29 -0
- scratch_next/game_server.py +134 -0
- scratch_next/models.py +171 -0
- scratch_next/security.py +159 -0
- scratch_next/session.py +109 -0
- scratch_next-3.0.0.dist-info/METADATA +44 -0
- scratch_next-3.0.0.dist-info/RECORD +18 -0
- scratch_next-3.0.0.dist-info/WHEEL +5 -0
- scratch_next-3.0.0.dist-info/entry_points.txt +2 -0
- scratch_next-3.0.0.dist-info/top_level.txt +1 -0
scratch_next/cli.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""
|
|
2
|
+
scratch_next.cli
|
|
3
|
+
================
|
|
4
|
+
ターミナルから直接操作できる scratch-next CLI
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import argparse
|
|
9
|
+
from . import __version__, get_user, get_project, Encoding, AnalyticsToolkit, ScratchUtilities
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> None:
|
|
13
|
+
parser = argparse.ArgumentParser(prog="scratch-next", description=f"scratch-next v{__version__} CLI")
|
|
14
|
+
sub = parser.add_subparsers(dest="cmd")
|
|
15
|
+
|
|
16
|
+
p_u = sub.add_parser("user", help="ユーザー情報取得")
|
|
17
|
+
p_u.add_argument("username")
|
|
18
|
+
|
|
19
|
+
p_p = sub.add_parser("project", help="プロジェクト統計&バイラルスコア診断")
|
|
20
|
+
p_p.add_argument("project_id", type=int)
|
|
21
|
+
|
|
22
|
+
p_e = sub.add_parser("encode", help="日本語・絵文字対応クラウド数値エンコード")
|
|
23
|
+
p_e.add_argument("text")
|
|
24
|
+
|
|
25
|
+
p_d = sub.add_parser("decode", help="クラウド数値デコード")
|
|
26
|
+
p_d.add_argument("digits")
|
|
27
|
+
|
|
28
|
+
p_url = sub.add_parser("parse-url", help="Scratch URL解析")
|
|
29
|
+
p_url.add_argument("url")
|
|
30
|
+
|
|
31
|
+
args = parser.parse_args()
|
|
32
|
+
if args.cmd == "user":
|
|
33
|
+
u = get_user(args.username)
|
|
34
|
+
u.update()
|
|
35
|
+
print(json.dumps({"username": u.username, "id": u.id, "scratchteam": u.scratchteam, "bio": u.about_me}, ensure_ascii=False, indent=2))
|
|
36
|
+
elif args.cmd == "project":
|
|
37
|
+
p = get_project(args.project_id)
|
|
38
|
+
p.update()
|
|
39
|
+
print(json.dumps({"id": p.id, "title": p.title, "author": p.author, "stats": p.stats, "viral": AnalyticsToolkit.project_viral_metrics(p.stats)}, ensure_ascii=False, indent=2))
|
|
40
|
+
elif args.cmd == "encode":
|
|
41
|
+
print(Encoding.encode(args.text))
|
|
42
|
+
elif args.cmd == "decode":
|
|
43
|
+
print(Encoding.decode(args.digits))
|
|
44
|
+
elif args.cmd == "parse-url":
|
|
45
|
+
print(json.dumps(ScratchUtilities.parse_scratch_url(args.url), ensure_ascii=False))
|
|
46
|
+
else:
|
|
47
|
+
parser.print_help()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
main()
|
scratch_next/cloud.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""
|
|
2
|
+
scratch_next.cloud
|
|
3
|
+
==================
|
|
4
|
+
F001-F015: 高速クラウドエンジン・多重化・スナップショット・リプレイ・TurboWarp対応
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import threading
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Callable, Dict, List, Optional, Union
|
|
12
|
+
from .cache_http import HTTPClient
|
|
13
|
+
from .exceptions import ScratchNextError, CloudConnectionError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class CloudEvent:
|
|
18
|
+
user: str
|
|
19
|
+
var: str
|
|
20
|
+
value: str
|
|
21
|
+
timestamp: float = field(default_factory=time.time)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class VirtualCloudSandbox:
|
|
25
|
+
"""F009: オフライン高速テスト用の仮想クラウドサーバー"""
|
|
26
|
+
def __init__(self, project_id: int = 0):
|
|
27
|
+
self.project_id = project_id
|
|
28
|
+
self._vars: Dict[str, str] = {}
|
|
29
|
+
self.audit_log: List[CloudEvent] = []
|
|
30
|
+
|
|
31
|
+
def set_var(self, variable: str, value: Union[int, float, str], user: str = "local_tester") -> None:
|
|
32
|
+
name = variable if variable.startswith("☁ ") else f"☁ {variable}"
|
|
33
|
+
val_str = str(value)
|
|
34
|
+
self._vars[name] = val_str
|
|
35
|
+
self.audit_log.append(CloudEvent(user=user, var=name, value=val_str))
|
|
36
|
+
|
|
37
|
+
def get_var(self, variable: str) -> Optional[str]:
|
|
38
|
+
name = variable if variable.startswith("☁ ") else f"☁ {variable}"
|
|
39
|
+
return self._vars.get(name)
|
|
40
|
+
|
|
41
|
+
def get_all_vars(self) -> Dict[str, str]:
|
|
42
|
+
return dict(self._vars)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CloudVariableMultiplexer:
|
|
46
|
+
"""F011: 1つのクラウド変数(256桁)に最大40個のサブ変数をパッキング多重化"""
|
|
47
|
+
@staticmethod
|
|
48
|
+
def pack(slots: Dict[str, int], width: int = 6) -> str:
|
|
49
|
+
parts = [f"{len(slots):02d}"]
|
|
50
|
+
for key in sorted(slots.keys()):
|
|
51
|
+
val = max(0, min(10**width - 1, int(slots[key])))
|
|
52
|
+
parts.append(f"{val:0{width}d}")
|
|
53
|
+
return "".join(parts)
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def unpack(packed_digits: str, keys: List[str], width: int = 6) -> Dict[str, int]:
|
|
57
|
+
s = str(packed_digits)
|
|
58
|
+
if len(s) < 2:
|
|
59
|
+
return {}
|
|
60
|
+
res = {}
|
|
61
|
+
idx = 2
|
|
62
|
+
for k in sorted(keys):
|
|
63
|
+
if idx + width <= len(s):
|
|
64
|
+
res[k] = int(s[idx : idx + width])
|
|
65
|
+
idx += width
|
|
66
|
+
return res
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class CloudConnection:
|
|
70
|
+
"""
|
|
71
|
+
F001: 指数バックオフ自動リトライ
|
|
72
|
+
F002: 0.1秒レート制限自動回避キュー
|
|
73
|
+
F004: スナップショット保存・復元
|
|
74
|
+
F005: 差分ウォッチャー (@cloud.on_set)
|
|
75
|
+
F007: RTT遅延計測
|
|
76
|
+
F012: 監査ログ
|
|
77
|
+
F013: 不正値検知時の自動ロールバック
|
|
78
|
+
F015: リプレイ再生
|
|
79
|
+
"""
|
|
80
|
+
CLOUDDATA_URL = "https://clouddata.scratch.mit.edu"
|
|
81
|
+
|
|
82
|
+
def __init__(self, project_id: int, http: HTTPClient, ws_host: str = "wss://clouddata.scratch.mit.edu"):
|
|
83
|
+
self.project_id = int(project_id)
|
|
84
|
+
self._http = http
|
|
85
|
+
self.ws_host = ws_host
|
|
86
|
+
self._vars: Dict[str, str] = {}
|
|
87
|
+
self._snapshots: Dict[str, Dict[str, str]] = {}
|
|
88
|
+
self._listeners: Dict[str, List[Callable[[CloudEvent], None]]] = {}
|
|
89
|
+
self._validators: Dict[str, Callable[[str], bool]] = {}
|
|
90
|
+
self.audit_logs: List[CloudEvent] = []
|
|
91
|
+
self._last_send_time = 0.0
|
|
92
|
+
self._lock = threading.Lock()
|
|
93
|
+
self.refresh_from_logs()
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def _norm(variable: str) -> str:
|
|
97
|
+
return variable if variable.startswith("☁ ") else f"☁ {variable}"
|
|
98
|
+
|
|
99
|
+
def measure_latency_ms(self) -> float:
|
|
100
|
+
t0 = time.perf_counter()
|
|
101
|
+
url = f"{self.CLOUDDATA_URL}/logs?projectid={self.project_id}&limit=1&offset=0"
|
|
102
|
+
self._http.request("GET", url)
|
|
103
|
+
return round((time.perf_counter() - t0) * 1000, 2)
|
|
104
|
+
|
|
105
|
+
def refresh_from_logs(self, limit: int = 100) -> List[CloudEvent]:
|
|
106
|
+
url = f"{self.CLOUDDATA_URL}/logs?projectid={self.project_id}&limit={limit}&offset=0"
|
|
107
|
+
logs = self._http.request("GET", url)
|
|
108
|
+
events: List[CloudEvent] = []
|
|
109
|
+
if isinstance(logs, list):
|
|
110
|
+
for entry in reversed(logs):
|
|
111
|
+
var_name = entry.get("name", "")
|
|
112
|
+
val = str(entry.get("value", ""))
|
|
113
|
+
user = entry.get("user", "unknown")
|
|
114
|
+
ts = float(entry.get("timestamp", time.time() * 1000)) / 1000.0
|
|
115
|
+
old_val = self._vars.get(var_name)
|
|
116
|
+
|
|
117
|
+
if var_name in self._validators and not self._validators[var_name](val):
|
|
118
|
+
if old_val is not None:
|
|
119
|
+
self.set_var(var_name, old_val)
|
|
120
|
+
continue
|
|
121
|
+
|
|
122
|
+
self._vars[var_name] = val
|
|
123
|
+
ev = CloudEvent(user=user, var=var_name, value=val, timestamp=ts)
|
|
124
|
+
events.append(ev)
|
|
125
|
+
self.audit_logs.append(ev)
|
|
126
|
+
if old_val != val:
|
|
127
|
+
for cb in self._listeners.get(var_name, []) + self._listeners.get("*", []):
|
|
128
|
+
cb(ev)
|
|
129
|
+
return events
|
|
130
|
+
|
|
131
|
+
def set_validator(self, variable: str, predicate: Callable[[str], bool]) -> None:
|
|
132
|
+
self._validators[self._norm(variable)] = predicate
|
|
133
|
+
|
|
134
|
+
def get_var(self, variable: str) -> Optional[str]:
|
|
135
|
+
self.refresh_from_logs(limit=25)
|
|
136
|
+
return self._vars.get(self._norm(variable))
|
|
137
|
+
|
|
138
|
+
def get_all_vars(self) -> Dict[str, str]:
|
|
139
|
+
self.refresh_from_logs(limit=100)
|
|
140
|
+
return dict(self._vars)
|
|
141
|
+
|
|
142
|
+
def set_var(self, variable: str, value: Union[int, float, str], max_retries: int = 3) -> None:
|
|
143
|
+
val_str = str(value)
|
|
144
|
+
if len(val_str) > 256:
|
|
145
|
+
raise ScratchNextError(f"Value length {len(val_str)} > 256 limit")
|
|
146
|
+
|
|
147
|
+
with self._lock:
|
|
148
|
+
elapsed = time.monotonic() - self._last_send_time
|
|
149
|
+
if elapsed < 0.105:
|
|
150
|
+
time.sleep(0.105 - elapsed)
|
|
151
|
+
|
|
152
|
+
var_name = self._norm(variable)
|
|
153
|
+
for attempt in range(max_retries):
|
|
154
|
+
try:
|
|
155
|
+
import websockets.sync.client as ws_sync # type: ignore
|
|
156
|
+
headers = {
|
|
157
|
+
"Cookie": f'scratchsessionsid="{self._http.session_id}";',
|
|
158
|
+
"Origin": "https://scratch.mit.edu",
|
|
159
|
+
}
|
|
160
|
+
with ws_sync.connect(self.ws_host, additional_headers=headers, open_timeout=8) as ws:
|
|
161
|
+
handshake_msg = json.dumps({
|
|
162
|
+
"method": "handshake",
|
|
163
|
+
"user": self._http.username,
|
|
164
|
+
"project_id": str(self.project_id),
|
|
165
|
+
}) + "\n"
|
|
166
|
+
set_msg = json.dumps({
|
|
167
|
+
"method": "set",
|
|
168
|
+
"user": self._http.username,
|
|
169
|
+
"project_id": str(self.project_id),
|
|
170
|
+
"name": var_name,
|
|
171
|
+
"value": val_str,
|
|
172
|
+
}) + "\n"
|
|
173
|
+
ws.send(handshake_msg)
|
|
174
|
+
ws.send(set_msg)
|
|
175
|
+
self._vars[var_name] = val_str
|
|
176
|
+
self._last_send_time = time.monotonic()
|
|
177
|
+
return
|
|
178
|
+
except ImportError:
|
|
179
|
+
raise CloudConnectionError("Install `websockets` (`pip install websockets`) for live WS writes.")
|
|
180
|
+
except Exception as e:
|
|
181
|
+
if attempt == max_retries - 1:
|
|
182
|
+
raise CloudConnectionError(f"Failed after {max_retries} attempts: {e}") from e
|
|
183
|
+
time.sleep(0.3 * (2 ** attempt))
|
|
184
|
+
|
|
185
|
+
def save_snapshot(self, name: str = "default") -> Dict[str, str]:
|
|
186
|
+
self._snapshots[name] = dict(self._vars)
|
|
187
|
+
return dict(self._vars)
|
|
188
|
+
|
|
189
|
+
def restore_snapshot(self, name: str = "default") -> None:
|
|
190
|
+
if name not in self._snapshots:
|
|
191
|
+
raise ScratchNextError(f"Snapshot '{name}' does not exist")
|
|
192
|
+
for k, v in self._snapshots[name].items():
|
|
193
|
+
self.set_var(k, v)
|
|
194
|
+
|
|
195
|
+
def on_set(self, variable: str = "*") -> Callable:
|
|
196
|
+
key = "*" if variable == "*" else self._norm(variable)
|
|
197
|
+
def decorator(fn: Callable[[CloudEvent], None]) -> Callable[[CloudEvent], None]:
|
|
198
|
+
self._listeners.setdefault(key, []).append(fn)
|
|
199
|
+
return fn
|
|
200
|
+
return decorator
|
|
201
|
+
|
|
202
|
+
def replay_events(self, events: List[CloudEvent], speed: float = 1.0) -> None:
|
|
203
|
+
for i, ev in enumerate(events):
|
|
204
|
+
if i > 0 and speed > 0:
|
|
205
|
+
dt = max(0.0, min(2.0, (ev.timestamp - events[i - 1].timestamp) / speed))
|
|
206
|
+
time.sleep(dt)
|
|
207
|
+
for cb in self._listeners.get(ev.var, []) + self._listeners.get("*", []):
|
|
208
|
+
cb(ev)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class TurboWarpCloudConnection(CloudConnection):
|
|
212
|
+
"""F003: TurboWarp クラウドサーバー接続"""
|
|
213
|
+
def __init__(self, project_id: int, http: HTTPClient):
|
|
214
|
+
super().__init__(project_id=project_id, http=http, ws_host="wss://clouddata.turbowarp.org")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class MultiProjectCloudMesh:
|
|
218
|
+
"""F006: 複数プロジェクト間のクラウド変数双方向メッシュ同期"""
|
|
219
|
+
def __init__(self, connections: List[CloudConnection]):
|
|
220
|
+
self.connections = connections
|
|
221
|
+
|
|
222
|
+
def sync_variable(self, variable: str, source_index: int = 0) -> None:
|
|
223
|
+
val = self.connections[source_index].get_var(variable)
|
|
224
|
+
if val is None:
|
|
225
|
+
return
|
|
226
|
+
for idx, conn in enumerate(self.connections):
|
|
227
|
+
if idx != source_index:
|
|
228
|
+
conn.set_var(variable, val)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""
|
|
2
|
+
scratch_next.exceptions
|
|
3
|
+
=======================
|
|
4
|
+
詳細エラー診断用の例外クラス階層
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ScratchNextError(Exception):
|
|
9
|
+
"""scratch-next 基底例外"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthenticationError(ScratchNextError):
|
|
13
|
+
"""認証・ログイン・セッションエラー"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CloudConnectionError(ScratchNextError):
|
|
17
|
+
"""クラウド変数・WebSocket通信エラー"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RateLimitError(ScratchNextError):
|
|
21
|
+
"""Scratch API レート制限 (HTTP 429) エラー"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SecurityViolationError(ScratchNextError):
|
|
25
|
+
"""アンチチート・署名検証・セーフモード違反"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ProjectASTError(ScratchNextError):
|
|
29
|
+
"""project.json 構文解析・操作エラー"""
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
scratch_next.game_server
|
|
3
|
+
========================
|
|
4
|
+
F076-F090: マルチプレイロビー・無限ランキング・通貨台帳・イロレーティング・20TPSサーバー
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import random
|
|
10
|
+
import threading
|
|
11
|
+
from typing import Callable, Dict, List, Optional, Tuple
|
|
12
|
+
from .ai_integrations import SQLiteCloudStorage
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MatchmakingLobby:
|
|
16
|
+
"""F076: オンライン自動マッチングロビー"""
|
|
17
|
+
def __init__(self, room_size: int = 2):
|
|
18
|
+
self.room_size = room_size
|
|
19
|
+
self._queue: List[str] = []
|
|
20
|
+
self.rooms: Dict[str, List[str]] = {}
|
|
21
|
+
|
|
22
|
+
def join_queue(self, username: str) -> Optional[str]:
|
|
23
|
+
u = username.lower()
|
|
24
|
+
if u not in self._queue:
|
|
25
|
+
self._queue.append(u)
|
|
26
|
+
if len(self._queue) >= self.room_size:
|
|
27
|
+
members = [self._queue.pop(0) for _ in range(self.room_size)]
|
|
28
|
+
room_id = f"room_{int(time.time() * 1000)}_{random.randint(100, 999)}"
|
|
29
|
+
self.rooms[room_id] = members
|
|
30
|
+
return room_id
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class GlobalLeaderboard:
|
|
35
|
+
"""F077: 無制限グローバルリーダーボード"""
|
|
36
|
+
def __init__(self, storage: Optional[SQLiteCloudStorage] = None):
|
|
37
|
+
self.db = storage or SQLiteCloudStorage()
|
|
38
|
+
|
|
39
|
+
def submit(self, board_name: str, username: str, score: float) -> float:
|
|
40
|
+
curr = self.db.get(f"lb_{board_name}", username, default=None)
|
|
41
|
+
best = max(float(curr), float(score)) if curr is not None else float(score)
|
|
42
|
+
self.db.put(f"lb_{board_name}", username, best)
|
|
43
|
+
return best
|
|
44
|
+
|
|
45
|
+
def get_top(self, board_name: str, limit: int = 10) -> List[Tuple[str, float]]:
|
|
46
|
+
with self.db._lock:
|
|
47
|
+
cur = self.db.conn.execute("SELECT key, val FROM kv_saves WHERE namespace=?", (f"lb_{board_name}",))
|
|
48
|
+
items = [(r[0], float(json.loads(r[1]))) for r in cur.fetchall()]
|
|
49
|
+
items.sort(key=lambda x: x[1], reverse=True)
|
|
50
|
+
return items[:limit]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PlayerPresenceTracker:
|
|
54
|
+
"""F080: ハートビート生存確認&自動タイムアウト離脱"""
|
|
55
|
+
def __init__(self, timeout_sec: float = 15.0):
|
|
56
|
+
self.timeout_sec = timeout_sec
|
|
57
|
+
self._last_seen: Dict[str, float] = {}
|
|
58
|
+
|
|
59
|
+
def heartbeat(self, username: str) -> None:
|
|
60
|
+
self._last_seen[username.lower()] = time.monotonic()
|
|
61
|
+
|
|
62
|
+
def online_players(self) -> List[str]:
|
|
63
|
+
now = time.monotonic()
|
|
64
|
+
active = [u for u, ts in self._last_seen.items() if now - ts <= self.timeout_sec]
|
|
65
|
+
self._last_seen = {u: self._last_seen[u] for u in active}
|
|
66
|
+
return active
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class VirtualEconomyLedger:
|
|
70
|
+
"""F081: ゲーム内通貨・アイテム取引台帳"""
|
|
71
|
+
def __init__(self, storage: Optional[SQLiteCloudStorage] = None):
|
|
72
|
+
self.db = storage or SQLiteCloudStorage()
|
|
73
|
+
|
|
74
|
+
def balance(self, username: str) -> int:
|
|
75
|
+
return int(self.db.get("economy_coins", username, default=0))
|
|
76
|
+
|
|
77
|
+
def grant(self, username: str, amount: int) -> int:
|
|
78
|
+
new_bal = max(0, self.balance(username) + amount)
|
|
79
|
+
self.db.put("economy_coins", username, new_bal)
|
|
80
|
+
return new_bal
|
|
81
|
+
|
|
82
|
+
def transfer(self, sender: str, receiver: str, amount: int) -> bool:
|
|
83
|
+
if amount <= 0 or self.balance(sender) < amount:
|
|
84
|
+
return False
|
|
85
|
+
self.grant(sender, -amount)
|
|
86
|
+
self.grant(receiver, amount)
|
|
87
|
+
return True
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class GameSystemsPack:
|
|
91
|
+
"""F084: ガチャ抽選 / F086: PvPイロレーティング / F088: 大会トーナメント表生成"""
|
|
92
|
+
@staticmethod
|
|
93
|
+
def roll_gacha(pool: Dict[str, float]) -> str:
|
|
94
|
+
return random.choices(list(pool.keys()), weights=list(pool.values()), k=1)[0]
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def calculate_elo(rating_a: float, rating_b: float, a_won: bool, k: float = 32.0) -> Tuple[float, float]:
|
|
98
|
+
expected_a = 1.0 / (1.0 + 10.0 ** ((rating_b - rating_a) / 400.0))
|
|
99
|
+
score_a = 1.0 if a_won else 0.0
|
|
100
|
+
new_a = round(rating_a + k * (score_a - expected_a), 1)
|
|
101
|
+
new_b = round(rating_b + k * ((1.0 - score_a) - (1.0 - expected_a)), 1)
|
|
102
|
+
return new_a, new_b
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def generate_tournament_bracket(players: List[str]) -> List[Tuple[str, str]]:
|
|
106
|
+
shuffled = list(players)
|
|
107
|
+
random.shuffle(shuffled)
|
|
108
|
+
if len(shuffled) % 2 == 1:
|
|
109
|
+
shuffled.append("BYE (不戦勝)")
|
|
110
|
+
return [(shuffled[i], shuffled[i + 1]) for i in range(0, len(shuffled), 2)]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ServerTickLoop:
|
|
114
|
+
"""F087: 20TPS 固定レートサーバーゲームループ"""
|
|
115
|
+
def __init__(self, tps: int = 20):
|
|
116
|
+
self.tps = max(1, tps)
|
|
117
|
+
self._running = False
|
|
118
|
+
|
|
119
|
+
def start(self, on_tick: Callable[[int], None]) -> None:
|
|
120
|
+
self._running = True
|
|
121
|
+
dt = 1.0 / self.tps
|
|
122
|
+
def _run():
|
|
123
|
+
tick = 0
|
|
124
|
+
while self._running:
|
|
125
|
+
t0 = time.perf_counter()
|
|
126
|
+
on_tick(tick)
|
|
127
|
+
tick += 1
|
|
128
|
+
sleep_time = dt - (time.perf_counter() - t0)
|
|
129
|
+
if sleep_time > 0:
|
|
130
|
+
time.sleep(sleep_time)
|
|
131
|
+
threading.Thread(target=_run, daemon=True).start()
|
|
132
|
+
|
|
133
|
+
def stop(self) -> None:
|
|
134
|
+
self._running = False
|
scratch_next/models.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""
|
|
2
|
+
scratch_next.models
|
|
3
|
+
===================
|
|
4
|
+
scratchattach 完全互換の User / Project / Studio リッチモデル
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, List, Optional
|
|
8
|
+
from .cache_http import HTTPClient
|
|
9
|
+
from .exceptions import AuthenticationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class User:
|
|
13
|
+
def __init__(self, username: str, http: HTTPClient):
|
|
14
|
+
self.username = username
|
|
15
|
+
self._http = http
|
|
16
|
+
self._raw: Optional[Dict[str, Any]] = None
|
|
17
|
+
|
|
18
|
+
def update(self) -> Dict[str, Any]:
|
|
19
|
+
self._raw = self._http.request("GET", f"{HTTPClient.BASE_API}/users/{self.username}", use_cache=True)
|
|
20
|
+
return self._raw or {}
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def id(self) -> Optional[int]:
|
|
24
|
+
return (self._raw or self.update()).get("id")
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def scratchteam(self) -> bool:
|
|
28
|
+
return bool((self._raw or self.update()).get("scratchteam", False))
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def about_me(self) -> str:
|
|
32
|
+
return (self._raw or self.update()).get("profile", {}).get("bio", "")
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def wiwo(self) -> str:
|
|
36
|
+
return (self._raw or self.update()).get("profile", {}).get("status", "")
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def joined_date(self) -> str:
|
|
40
|
+
return (self._raw or self.update()).get("history", {}).get("joined", "")
|
|
41
|
+
|
|
42
|
+
def projects(self, limit: int = 20, offset: int = 0) -> List[Dict[str, Any]]:
|
|
43
|
+
return self._http.request(
|
|
44
|
+
"GET", f"{HTTPClient.BASE_API}/users/{self.username}/projects?limit={limit}&offset={offset}", use_cache=True
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def followers(self, limit: int = 40, offset: int = 0) -> List[Dict[str, Any]]:
|
|
48
|
+
return self._http.request(
|
|
49
|
+
"GET", f"{HTTPClient.BASE_API}/users/{self.username}/followers?limit={limit}&offset={offset}", use_cache=True
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def following(self, limit: int = 40, offset: int = 0) -> List[Dict[str, Any]]:
|
|
53
|
+
return self._http.request(
|
|
54
|
+
"GET", f"{HTTPClient.BASE_API}/users/{self.username}/following?limit={limit}&offset={offset}", use_cache=True
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def follow(self) -> Any:
|
|
58
|
+
if not self._http.username:
|
|
59
|
+
raise AuthenticationError("Login required")
|
|
60
|
+
return self._http.request(
|
|
61
|
+
"PUT", f"{HTTPClient.BASE_SITE}/site-api/users/followers/{self.username}/add/?usernames={self._http.username}"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def unfollow(self) -> Any:
|
|
65
|
+
if not self._http.username:
|
|
66
|
+
raise AuthenticationError("Login required")
|
|
67
|
+
return self._http.request(
|
|
68
|
+
"PUT", f"{HTTPClient.BASE_SITE}/site-api/users/followers/{self.username}/remove/?usernames={self._http.username}"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def post_comment(self, content: str, parent_id: str = "", commentee_id: str = "") -> Any:
|
|
72
|
+
return self._http.request(
|
|
73
|
+
"POST",
|
|
74
|
+
f"{HTTPClient.BASE_SITE}/site-api/comments/user/{self.username}/add/",
|
|
75
|
+
{"content": content, "parent_id": parent_id, "commentee_id": commentee_id},
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Project:
|
|
80
|
+
def __init__(self, project_id: int, http: HTTPClient):
|
|
81
|
+
self.id = int(project_id)
|
|
82
|
+
self._http = http
|
|
83
|
+
self._raw: Optional[Dict[str, Any]] = None
|
|
84
|
+
|
|
85
|
+
def update(self) -> Dict[str, Any]:
|
|
86
|
+
self._raw = self._http.request("GET", f"{HTTPClient.BASE_API}/projects/{self.id}", use_cache=True)
|
|
87
|
+
return self._raw or {}
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def title(self) -> str:
|
|
91
|
+
return (self._raw or self.update()).get("title", "")
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def instructions(self) -> str:
|
|
95
|
+
return (self._raw or self.update()).get("instructions", "")
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def notes(self) -> str:
|
|
99
|
+
return (self._raw or self.update()).get("description", "")
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def author(self) -> str:
|
|
103
|
+
return (self._raw or self.update()).get("author", {}).get("username", "")
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def stats(self) -> Dict[str, int]:
|
|
107
|
+
return (self._raw or self.update()).get("stats", {})
|
|
108
|
+
|
|
109
|
+
def get_json(self) -> Dict[str, Any]:
|
|
110
|
+
meta = self.update()
|
|
111
|
+
token = meta.get("project_token", "")
|
|
112
|
+
url = f"https://projects.scratch.mit.edu/{self.id}" + (f"?token={token}" if token else "")
|
|
113
|
+
return self._http.request("GET", url)
|
|
114
|
+
|
|
115
|
+
def get_ast_toolkit(self):
|
|
116
|
+
from .ast_tools import ProjectJSONToolkit
|
|
117
|
+
return ProjectJSONToolkit(self.get_json())
|
|
118
|
+
|
|
119
|
+
def love(self) -> Any:
|
|
120
|
+
return self._http.request("POST", f"{HTTPClient.BASE_API}/proxy/projects/{self.id}/loves/user/{self._http.username}")
|
|
121
|
+
|
|
122
|
+
def unlove(self) -> Any:
|
|
123
|
+
return self._http.request("DELETE", f"{HTTPClient.BASE_API}/proxy/projects/{self.id}/loves/user/{self._http.username}")
|
|
124
|
+
|
|
125
|
+
def favorite(self) -> Any:
|
|
126
|
+
return self._http.request("POST", f"{HTTPClient.BASE_API}/proxy/projects/{self.id}/favorites/user/{self._http.username}")
|
|
127
|
+
|
|
128
|
+
def post_comment(self, content: str, parent_id: str = "", commentee_id: str = "") -> Any:
|
|
129
|
+
return self._http.request(
|
|
130
|
+
"POST",
|
|
131
|
+
f"{HTTPClient.BASE_API}/proxy/comments/project/{self.id}",
|
|
132
|
+
{"content": content, "parent_id": parent_id, "commentee_id": commentee_id},
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def comments(self, limit: int = 20, offset: int = 0) -> List[Dict[str, Any]]:
|
|
136
|
+
return self._http.request(
|
|
137
|
+
"GET", f"{HTTPClient.BASE_API}/users/{self.author}/projects/{self.id}/comments?limit={limit}&offset={offset}"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class Studio:
|
|
142
|
+
def __init__(self, studio_id: int, http: HTTPClient):
|
|
143
|
+
self.id = int(studio_id)
|
|
144
|
+
self._http = http
|
|
145
|
+
self._raw: Optional[Dict[str, Any]] = None
|
|
146
|
+
|
|
147
|
+
def update(self) -> Dict[str, Any]:
|
|
148
|
+
self._raw = self._http.request("GET", f"{HTTPClient.BASE_API}/studios/{self.id}", use_cache=True)
|
|
149
|
+
return self._raw or {}
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def title(self) -> str:
|
|
153
|
+
return (self._raw or self.update()).get("title", "")
|
|
154
|
+
|
|
155
|
+
def projects(self, limit: int = 20, offset: int = 0) -> List[Dict[str, Any]]:
|
|
156
|
+
return self._http.request(
|
|
157
|
+
"GET", f"{HTTPClient.BASE_API}/studios/{self.id}/projects?limit={limit}&offset={offset}", use_cache=True
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def add_project(self, project_id: int) -> Any:
|
|
161
|
+
return self._http.request("POST", f"{HTTPClient.BASE_API}/studios/{self.id}/project/{project_id}")
|
|
162
|
+
|
|
163
|
+
def remove_project(self, project_id: int) -> Any:
|
|
164
|
+
return self._http.request("DELETE", f"{HTTPClient.BASE_API}/studios/{self.id}/project/{project_id}")
|
|
165
|
+
|
|
166
|
+
def post_comment(self, content: str, parent_id: str = "", commentee_id: str = "") -> Any:
|
|
167
|
+
return self._http.request(
|
|
168
|
+
"POST",
|
|
169
|
+
f"{HTTPClient.BASE_API}/proxy/comments/studio/{self.id}",
|
|
170
|
+
{"content": content, "parent_id": parent_id, "commentee_id": commentee_id},
|
|
171
|
+
)
|