Skip to main content

ruxla_env/
breakout.rs

1//! Breakout, following gymnax's `Breakout-MinAtar`.
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/// `jnp.array(table)[i]`: an element of a constant table at a run-time
9/// index (JAX's indexing).
10#[inline]
11fn lookup<B: Backend, const N: usize>(table: [i32; N], i: I32<B>) -> I32<B> {
12    Array::<B, i32>::from_slice(&table, [N]).get(i)
13}
14
15/// `jnp.count_nonzero(x)`: the number of nonzero elements, as `i32`.
16fn count_nonzero<B: Backend>(x: &Array<B, f32>) -> I32<B> {
17    jnp::sum(x.ne(0.0f32).cast::<i32>(), jnp::ALL).to_scalar()
18}
19
20/// The state of a Breakout episode. The fields are in the order of gymnax's
21/// `EnvState` leaves.
22#[derive(Clone, Debug, Tree)]
23pub struct BreakoutState<B: Backend> {
24    /// Steps taken in the episode.
25    pub time: I32<B>,
26    /// The row of the ball.
27    pub ball_y: I32<B>,
28    /// The column of the ball.
29    pub ball_x: I32<B>,
30    /// The direction of the ball: 0 up-left, 1 up-right, 2 down-right,
31    /// 3 down-left.
32    pub ball_dir: I32<B>,
33    /// The column of the paddle.
34    pub pos: I32<B>,
35    /// The bricks (`f32[10, 10]`, ones where a brick is).
36    pub brick_map: Array<B, f32>,
37    /// Whether the ball hit a brick in the previous step.
38    pub strike: Bool<B>,
39    /// The previous row of the ball.
40    pub last_y: I32<B>,
41    /// The previous column of the ball.
42    pub last_x: I32<B>,
43    /// Whether the episode ended.
44    pub terminal: Bool<B>,
45}
46
47/// The parameters of Breakout.
48#[derive(Clone, Debug, Tree)]
49pub struct BreakoutParams<B: Backend> {
50    /// The time limit.
51    pub max_steps_in_episode: I32<B>,
52}
53
54/// gymnax's Breakout (`Breakout-MinAtar`): move a paddle at the bottom of a
55/// 10x10 grid to bounce a ball into three rows of bricks. Actions: no-op
56/// (0), left (1), right (2). The observation is `f32[10, 10, 4]` with the
57/// channels paddle, ball, trail, and bricks (gymnax converts its boolean
58/// grid to `f32`).
59///
60/// It reproduces gymnax 1.0 with the same operations (with the minimal
61/// action set), so the same keys and actions give the same trajectories.
62#[derive(Clone, Copy, Debug, Default)]
63pub struct Breakout;
64
65/// The full action of each minimal action (`['n', 'l', 'r']`).
66const ACTION_SET: [i32; 3] = [0, 1, 3];
67
68impl Breakout {
69    fn observation<B: Backend>(&self, s: &BreakoutState<B>) -> Array<B, f32> {
70        let mut obs = jnp::zeros::<B, bool>([10, 10, 4]);
71        obs.at_mut((9i64, s.pos, 0i64)).set(true);
72        obs.at_mut((s.ball_y, s.ball_x, 1i64)).set(true);
73        obs.at_mut((s.last_y, s.last_x, 2i64)).set(true);
74        obs.at_mut((.., .., 3i64)).set(s.brick_map.cast::<bool>());
75        obs.cast::<f32>()
76    }
77
78    /// `jnp.zeros((10, 10)).at[1:4, :].set(1)`.
79    fn initial_bricks<B: Backend>(&self) -> Array<B, f32> {
80        jnp::zeros::<B, f32>([10, 10])
81            .into_at((1i64..4, ..))
82            .set(1.0f32)
83    }
84
85    /// gymnax's `step_agent`: moves the paddle and the ball (in x), and
86    /// returns the state with the new paddle, trail, and direction, and the
87    /// new ball position.
88    fn step_agent<B: Backend>(
89        &self,
90        s: &BreakoutState<B>,
91        action: I32<B>,
92    ) -> (BreakoutState<B>, I32<B>, I32<B>) {
93        let int = |b: Bool<B>| b.cast::<i32>();
94        let pos = (s.pos - 1).max(0) * int(action.eq(1))
95            + (s.pos + 1).min(9) * int(action.eq(3))
96            + s.pos * int(action.ne(1) & action.ne(3));
97        let (x, y, d) = (s.ball_x, s.ball_y, s.ball_dir);
98        let new_x = (x - 1) * int(d.eq(0))
99            + (x + 1) * int(d.eq(1))
100            + (x + 1) * int(d.eq(2))
101            + (x - 1) * int(d.eq(3));
102        let new_y = (y - 1) * int(d.eq(0))
103            + (y - 1) * int(d.eq(1))
104            + (y + 1) * int(d.eq(2))
105            + (y + 1) * int(d.eq(3));
106        let border_cond_x = new_x.lt(0) | new_x.gt(9);
107        // gymnax's `0 * (new_x < 0) + 9 * (new_x > 9)`.
108        let new_x = lax::select(border_cond_x, 9 * int(new_x.gt(9)), new_x);
109        let ball_dir = lax::select(border_cond_x, lookup([1, 0, 3, 2], d), d);
110        let state = BreakoutState {
111            pos,
112            last_x: x,
113            last_y: y,
114            ball_dir,
115            ..s.clone()
116        };
117        (state, new_x, new_y)
118    }
119
120    /// gymnax's `step_ball_brick`: bounces the ball off the walls, bricks,
121    /// and paddle, and returns the state and the reward.
122    fn step_ball_brick<B: Backend>(
123        &self,
124        s: BreakoutState<B>,
125        new_x: I32<B>,
126        new_y: I32<B>,
127    ) -> (BreakoutState<B>, F32<B>) {
128        let reflect = |d: I32<B>| lookup([3, 2, 1, 0], d);
129        let border_cond1_y = new_y.lt(0);
130        let new_y = lax::select(border_cond1_y, 0, new_y);
131        let ball_dir = lax::select(border_cond1_y, reflect(s.ball_dir), s.ball_dir);
132
133        // Brick collision.
134        let strike_toggle = !border_cond1_y & s.brick_map.get((new_y, new_x)).eq(1.0);
135        let strike_bool = !s.strike & strike_toggle;
136        let reward = strike_bool.cast::<f32>();
137        let struck = s.brick_map.at((new_y, new_x)).set(0.0f32);
138        let brick_map = lax::select_array(&strike_bool.to_array(), &struck, &s.brick_map);
139        let new_y = lax::select(strike_bool, s.last_y, new_y);
140        let ball_dir = lax::select(strike_bool, reflect(ball_dir), ball_dir);
141
142        // Wall collision.
143        let brick_cond = !strike_toggle & new_y.eq(9);
144        // New bricks if every brick is gone.
145        let spawn_bricks = brick_cond & count_nonzero(&brick_map).eq(0);
146        let refilled = brick_map.at((1i64..4, ..)).set(1.0f32);
147        let brick_map = lax::select_array(&spawn_bricks.to_array(), &refilled, &brick_map);
148        // The ball hits the old paddle position.
149        let redirect_ball1 = brick_cond & s.ball_x.eq(s.pos);
150        let ball_dir = lax::select(redirect_ball1, reflect(ball_dir), ball_dir);
151        let new_y = lax::select(redirect_ball1, s.last_y, new_y);
152        // The ball hits the new paddle position.
153        let redirect_ball2a = brick_cond & !redirect_ball1;
154        let redirect_ball2 = redirect_ball2a & new_x.eq(s.pos);
155        let ball_dir = lax::select(redirect_ball2, lookup([2, 3, 0, 1], ball_dir), ball_dir);
156        let new_y = lax::select(redirect_ball2, s.last_y, new_y);
157        let redirect_cond = !redirect_ball1 & !redirect_ball2;
158        let terminal = brick_cond & redirect_cond;
159
160        let state = BreakoutState {
161            ball_dir,
162            brick_map,
163            strike: strike_toggle,
164            ball_x: new_x,
165            ball_y: new_y,
166            terminal,
167            ..s
168        };
169        (state, reward)
170    }
171}
172
173impl Environment for Breakout {
174    type State<B: Backend> = BreakoutState<B>;
175    type Params<B: Backend> = BreakoutParams<B>;
176    type Obs<B: Backend> = Array<B, f32>;
177    type Action<B: Backend> = I32<B>;
178
179    fn name(&self) -> &str {
180        "Breakout-MinAtar"
181    }
182
183    fn action_space(&self) -> ActionSpace {
184        ActionSpace::Discrete(ACTION_SET.len())
185    }
186
187    fn default_params<B: Backend>(&self) -> BreakoutParams<B> {
188        BreakoutParams {
189            max_steps_in_episode: I32::new(1000),
190        }
191    }
192
193    fn reset<B: Backend>(
194        &self,
195        key: Key<B>,
196        _params: &BreakoutParams<B>,
197    ) -> (Array<B, f32>, BreakoutState<B>) {
198        // `jax.random.choice(key, jnp.array([0, 1]))` draws an index with
199        // `randint` and takes it from the array, which is the index itself.
200        let ball_start = random::randint(&key, [], 0i32, 2).to_scalar();
201        let ball_x = lookup([0, 9], ball_start);
202        let state = BreakoutState {
203            time: I32::new(0),
204            ball_y: I32::new(3),
205            ball_x,
206            ball_dir: lookup([2, 3], ball_start),
207            pos: I32::new(4),
208            brick_map: self.initial_bricks(),
209            strike: Bool::new(false),
210            last_y: I32::new(3),
211            last_x: ball_x,
212            terminal: Bool::new(false),
213        };
214        (self.observation(&state), state)
215    }
216
217    fn step_env<B: Backend>(
218        &self,
219        _key: Key<B>,
220        s: &BreakoutState<B>,
221        action: I32<B>,
222        _params: &BreakoutParams<B>,
223    ) -> Transition<B, BreakoutState<B>, Array<B, f32>> {
224        let a = lookup(ACTION_SET, action);
225        let (state, new_x, new_y) = self.step_agent(s, a);
226        let (mut state, reward) = self.step_ball_brick(state, new_x, new_y);
227        state.time = state.time + 1;
228        let terminated = state.terminal;
229        Transition {
230            obs: self.observation(&state),
231            state,
232            reward,
233            terminated,
234        }
235    }
236
237    fn step_env_uses_key(&self) -> bool {
238        false
239    }
240
241    fn is_truncated<B: Backend>(&self, s: &BreakoutState<B>, p: &BreakoutParams<B>) -> Bool<B> {
242        s.time.ge(p.max_steps_in_episode)
243    }
244}