Skip to main content

ruxla_env/
tic_tac_toe.rs

1//! Tic-tac-toe, following Pgx's `tic_tac_toe`.
2
3use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Bool, F32, I32, Tree, jnp, lax};
5
6use crate::{ActionSpace, Environment, Transition};
7
8/// Pgx's `Env.step` around the game's `_step`: the reward of the player who
9/// acted (`current_player`), with Pgx's penalty of −1 for an illegal action,
10/// and whether the episode ended. `rewards` is Pgx's reward vector after
11/// `_step` (zeros unless `terminated`).
12fn two_player_outcome<B: Backend>(
13    is_illegal: Bool<B>,
14    current_player: I32<B>,
15    rewards: &Array<B, f32>,
16    terminated: Bool<B>,
17) -> (F32<B>, Bool<B>) {
18    let reward = lax::select(is_illegal, F32::new(-1.0), rewards.get(current_player));
19    (reward, terminated | is_illegal)
20}
21
22/// Pgx's `legal_action_mask` after a step: all ones where the episode
23/// ended.
24fn mask_after<B: Backend>(terminated: Bool<B>, mask: Array<B, bool>) -> Array<B, bool> {
25    jnp::where_(terminated, true, mask)
26}
27
28/// The state of a game of tic-tac-toe: Pgx's `State` without the
29/// observation and the rewards (which `step` returns), in the order of its
30/// leaves.
31#[derive(Clone, Debug, Tree)]
32pub struct TicTacToeState<B: Backend> {
33    /// The player to move (0 or 1).
34    pub current_player: I32<B>,
35    /// The empty cells (`bool[9]`; all ones after the game ended).
36    pub legal_action_mask: Array<B, bool>,
37    /// Steps taken in the game.
38    pub step_count: I32<B>,
39    /// The mark to place: 0 (X) or 1 (O).
40    pub color: I32<B>,
41    /// The cells in row-major order (`i32[9]`): -1 empty, 0 X, 1 O.
42    pub board: Array<B, i32>,
43    /// The mark that won, or -1.
44    pub winner: I32<B>,
45}
46
47/// Pgx's tic-tac-toe (`tic_tac_toe`): two players place marks on a 3x3
48/// board; three in a row wins (+1, and −1 for the other player). Action
49/// `i` places a mark on cell `i` (row-major). The observation is
50/// `bool[3, 3, 2]`: the current player's marks and the opponent's. The
51/// first player is random.
52///
53/// It reproduces Pgx 2.6 with the same operations. Pgx's environments have
54/// no automatic reset and give rewards to every player; this one is wrapped
55/// as Pgx's `pgx.experimental.auto_reset` does: `step` splits the key into
56/// `(key_step, key_reset)`, takes Pgx's `step(state, action, key_step)`,
57/// and starts a new game with `init(key_reset)` where one ended. The
58/// observation is Pgx's `observation` (the view of the current player), the
59/// reward is the reward of the player who acted, and
60/// [`legal_action_mask`](Environment::legal_action_mask) is Pgx's
61/// `legal_action_mask`. An illegal action ends the game with Pgx's penalty:
62/// −1 for the player who acted and +1 for the other.
63#[derive(Clone, Copy, Debug, Default)]
64pub struct TicTacToe;
65
66/// The lines of three cells.
67const LINES: [i32; 24] = [
68    0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 3, 6, 1, 4, 7, 2, 5, 8, 0, 4, 8, 2, 4, 6,
69];
70
71impl TicTacToe {
72    fn observation<B: Backend>(&self, s: &TicTacToeState<B>) -> Array<B, bool> {
73        // Pgx observes for the current player, whose mark is `color`.
74        let mine = s.board.eq(s.color);
75        let theirs = s.board.eq(1 - s.color);
76        jnp::stack(&[mine, theirs], -1).reshape([3, 3, 2])
77    }
78}
79
80impl Environment for TicTacToe {
81    type State<B: Backend> = TicTacToeState<B>;
82    type Params<B: Backend> = ();
83    type Obs<B: Backend> = Array<B, bool>;
84    type Action<B: Backend> = I32<B>;
85
86    fn name(&self) -> &str {
87        "tic_tac_toe"
88    }
89
90    fn action_space(&self) -> ActionSpace {
91        ActionSpace::Discrete(9)
92    }
93
94    fn default_params<B: Backend>(&self) {}
95
96    fn step_env_uses_key(&self) -> bool {
97        false
98    }
99
100    fn reset<B: Backend>(&self, key: Key<B>, _params: &()) -> (Array<B, bool>, TicTacToeState<B>) {
101        let first = random::bernoulli::<B, f32>(&key, 0.5f32, []).cast::<i32>();
102        let state = TicTacToeState {
103            current_player: first.to_scalar(),
104            legal_action_mask: jnp::full([9], true),
105            step_count: I32::new(0),
106            color: I32::new(0),
107            board: jnp::full([9], -1),
108            winner: I32::new(-1),
109        };
110        (self.observation(&state), state)
111    }
112
113    fn step_env<B: Backend>(
114        &self,
115        _key: Key<B>,
116        s: &TicTacToeState<B>,
117        action: I32<B>,
118        _params: &(),
119    ) -> Transition<B, TicTacToeState<B>, Array<B, bool>> {
120        let is_illegal = !s.legal_action_mask.get(action);
121        let board = s.board.at(action).set(s.color);
122        let lines = Array::<B, i32>::from_slice(&LINES, [8, 3]);
123        let won = jnp::any(
124            jnp::all(jnp::take(&board, &lines, 0).eq(s.color), 1),
125            jnp::ALL,
126        )
127        .to_scalar();
128        let winner = lax::select(won, s.color, -1);
129        let current_player = (s.current_player + 1) % 2;
130        let color = (s.color + 1) % 2;
131        let terminated = winner.ge(0) | jnp::all(board.ne(-1), jnp::ALL).to_scalar();
132        // The rewards of the players (by player, not by mark), zeros unless
133        // the game ended.
134        let should_flip = current_player.ne(color);
135        let by_mark = jnp::where_(jnp::arange::<B, i32>(2).eq(winner), 1.0f32, -1.0f32);
136        let flipped = jnp::stack(&[by_mark.get(1i64), by_mark.get(0i64)], 0);
137        let rewards = jnp::where_(should_flip, flipped, by_mark);
138        let rewards = jnp::where_(winner.ge(0) & terminated, rewards, 0.0f32);
139        let (reward, terminated) =
140            two_player_outcome(is_illegal, s.current_player, &rewards, terminated);
141        let state = TicTacToeState {
142            current_player,
143            legal_action_mask: mask_after(terminated, board.lt(0)),
144            step_count: s.step_count + 1,
145            color,
146            board,
147            winner,
148        };
149        Transition {
150            obs: self.observation(&state),
151            state,
152            reward,
153            terminated,
154        }
155    }
156
157    fn is_truncated<B: Backend>(&self, _s: &TicTacToeState<B>, _p: &()) -> Bool<B> {
158        Bool::new(false)
159    }
160
161    fn legal_action_mask<B: Backend>(&self, s: &TicTacToeState<B>) -> Option<Array<B, bool>> {
162        Some(s.legal_action_mask.clone())
163    }
164}