1use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Bool, F32, I32, Tree, jnp, lax};
5
6use crate::{ActionSpace, Environment, Transition};
7
8fn 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
22fn mask_after<B: Backend>(terminated: Bool<B>, mask: Array<B, bool>) -> Array<B, bool> {
25 jnp::where_(terminated, true, mask)
26}
27
28#[derive(Clone, Debug, Tree)]
32pub struct TicTacToeState<B: Backend> {
33 pub current_player: I32<B>,
35 pub legal_action_mask: Array<B, bool>,
37 pub step_count: I32<B>,
39 pub color: I32<B>,
41 pub board: Array<B, i32>,
43 pub winner: I32<B>,
45}
46
47#[derive(Clone, Copy, Debug, Default)]
64pub struct TicTacToe;
65
66const 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 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 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}