File size: 6,452 Bytes
c755ba9 | 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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
Chess Environment Implementation.
An RL agent plays White against a random bot (Black).
Reward is shaped: per-move material delta + terminal win/loss/draw bonus.
"""
import random
from typing import List
from uuid import uuid4
import chess
from openenv_core.env_server.interfaces import Environment
from openenv_core.env_server.types import State
from models import ChessAction, ChessObservation
# Piece values: P=1, N=3, B=3, R=5, Q=9
PIECE_VALUES = {
chess.PAWN: 1,
chess.KNIGHT: 3,
chess.BISHOP: 3,
chess.ROOK: 5,
chess.QUEEN: 9,
}
class ChessEnvironment(Environment):
"""
Chess environment where an RL agent (White) plays against a random bot (Black).
Reward shaping:
- material_delta: change in (White material - Black material) each step
- terminal bonus: +1 for win, -1 for loss, 0 for draw
"""
def __init__(self):
self._board = chess.Board()
self._state = State(episode_id=str(uuid4()), step_count=0)
self._captured_pieces: List[str] = []
def reset(self) -> ChessObservation:
self._board = chess.Board()
self._state = State(episode_id=str(uuid4()), step_count=0)
self._captured_pieces = []
return ChessObservation(
board_fen=self._board.fen(),
legal_moves=[m.uci() for m in self._board.legal_moves],
white_move="",
black_move=None,
material_balance=0.0,
game_status="ongoing",
captured_pieces=[],
done=False,
reward=0.0,
)
def step(self, action: ChessAction) -> ChessObservation: # type: ignore[override]
# --- validate ---
try:
move = chess.Move.from_uci(action.move)
except (chess.InvalidMoveError, ValueError) as exc:
raise ValueError(f"Invalid UCI string: {action.move!r}") from exc
if move not in self._board.legal_moves:
raise ValueError(
f"Illegal move: {action.move!r}. "
f"Legal moves: {[m.uci() for m in self._board.legal_moves]}"
)
self._state.step_count += 1
balance_before = self._material_balance()
# --- White's move ---
self._track_capture(move)
self._board.push(move)
white_uci = action.move
# check if game ended after White's move
status = self._get_game_status()
if self._is_terminal_status(status):
balance_after = self._material_balance()
material_delta = balance_after - balance_before
reward = material_delta + self._terminal_reward(status)
return ChessObservation(
board_fen=self._board.fen(),
legal_moves=[],
white_move=white_uci,
black_move=None,
material_balance=balance_after,
game_status=status,
captured_pieces=list(self._captured_pieces),
done=True,
reward=reward,
)
# --- Black's move (random) ---
black_moves = list(self._board.legal_moves)
black_move = random.choice(black_moves)
self._track_capture(black_move)
self._board.push(black_move)
black_uci = black_move.uci()
# --- post-move evaluation ---
status = self._get_game_status()
balance_after = self._material_balance()
material_delta = balance_after - balance_before
terminal = self._is_terminal_status(status)
reward = material_delta + (self._terminal_reward(status) if terminal else 0.0)
return ChessObservation(
board_fen=self._board.fen(),
legal_moves=[m.uci() for m in self._board.legal_moves] if not terminal else [],
white_move=white_uci,
black_move=black_uci,
material_balance=balance_after,
game_status=status,
captured_pieces=list(self._captured_pieces),
done=terminal,
reward=reward,
)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def _track_capture(self, move: chess.Move) -> None:
"""Record a captured piece symbol (handles en passant)."""
board = self._board
if board.is_en_passant(move):
self._captured_pieces.append(chess.piece_symbol(chess.PAWN))
elif board.piece_at(move.to_square) is not None:
self._captured_pieces.append(board.piece_at(move.to_square).symbol())
def _material_balance(self) -> float:
"""Return White material minus Black material."""
white = 0.0
black = 0.0
for sq in chess.SQUARES:
piece = self._board.piece_at(sq)
if piece is None:
continue
val = PIECE_VALUES.get(piece.piece_type, 0)
if piece.color == chess.WHITE:
white += val
else:
black += val
return white - black
def _get_game_status(self) -> str:
b = self._board
if b.is_checkmate():
return "checkmate"
if b.is_stalemate():
return "stalemate"
if b.is_insufficient_material():
return "draw_insufficient"
if b.is_fifty_moves():
return "draw_fifty"
if b.is_repetition():
return "draw_repetition"
if b.is_check():
return "check"
return "ongoing"
@staticmethod
def _is_terminal_status(status: str) -> bool:
return status in ("checkmate", "stalemate", "draw_insufficient",
"draw_fifty", "draw_repetition")
def _terminal_reward(self, status: str) -> float:
if status == "checkmate":
# whoever is to move is in checkmate → they lost
if self._board.turn == chess.BLACK:
return 1.0 # White delivered checkmate
else:
return -1.0 # Black delivered checkmate
# all other terminal states are draws
return 0.0
@property
def state(self) -> State:
return self._state
|