txlyre 1 day ago
parent
commit
a631b7c5c0
2 changed files with 35 additions and 2 deletions
  1. 10 2
      chess0.py
  2. 25 0
      commands.py

+ 10 - 2
chess0.py

@@ -94,8 +94,9 @@ class ChessSession:
 
         self.check_game_over()
 
-    def from_moves(self, moves, strict=True):
-        self.board.reset()
+    def from_moves(self, moves, strict=True, reset=True):
+        if reset:
+            self.board.reset()
 
         moves = moves.strip()
         if re.match(r"^[0-9]{1,3}$", moves):
@@ -196,6 +197,13 @@ class ChessManager:
 
         return True
 
+    def set(self, id, moves, strict=True, reset=False):
+        session = self.sessions.get(id)
+        if not session:
+            raise KeyError(id)
+
+        session.from_moves(moves, strict=strict, reset=reset)
+
     async def move(self, id, move=None):
         session = self.sessions.get(id)
         if not session:

+ 25 - 0
commands.py

@@ -846,6 +846,30 @@ async def chess_moves_handler(chess, id):
     return [text]
 
 
+async def chess_set_handler(chess, id, moves):
+    try:
+        await chess.set(id, moves, strict=not isinstance(id, str))
+    except GameOver as e:
+        return chess_game_over(chess, id, e)
+    except IllegalMove as e:
+        move = str(e)
+
+        if move:
+            return [f"Некорректный ход: {move}"]
+
+        return ["Некорректная последовательность ходов."]
+
+    reply = chess_render(chess, id)
+
+    if chess.is_check(id):
+        reply.append("Шах!")
+
+    if isinstance(id, str):
+        reply.append(f"Ход {'белых' if chess.turn(id) else 'чёрных'}.")
+
+    return reply
+
+
 async def chess_anim_handler(chess, id, arg):
     count = None
 
@@ -885,6 +909,7 @@ CHESS_COMMANDS = {
     "pass": (chess_pass_handler, "Сделать ход вместо вас", 0),
     "board": (chess_board_handler, "Показать доску", 0),
     "moves": (chess_moves_handler, "Показать историю ходов и состояние игры", 0),
+    "set": (chess_set_handler, "Установить состояние доски", 1, True),
 
     "create": (chess_start_handler, "Создать общую доску", 0),
     "createfrom": (chess_from_handler, "Создать общую доску в указанном состоянии", 1, True),