summaryrefslogtreecommitdiff
path: root/src/state.rs
blob: 87f73f59bb2fe769b2c1595229f9fa79d7497ab0 (plain)
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use crate::command::Command;
use crate::consts::*;
use std::collections::BTreeSet;
use std::ops::Bound::{Excluded, Included};
use std::rc::Rc;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum GameStatus {
    Continue,
    PlayerOneWon,
    PlayerTwoWon,
    Draw, // Until I add score I guess
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct GameState {
    pub status: GameStatus,
    pub players: [Player; 2],
    pub obstacles: Rc<BTreeSet<Position>>,
    pub powerup_oils: Rc<BTreeSet<Position>>,
    pub powerup_boosts: Rc<BTreeSet<Position>>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Player {
    pub position: Position,
    pub speed: u16,
    pub boost_remaining: u8,
    pub oils: u16,
    pub boosts: u16,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Position {
    pub y: u8,
    pub x: u16,
}

impl GameState {
    pub fn update(&mut self, commands: [Command; 2]) {
        if self.status != GameStatus::Continue {
            return;
        }

        let next_positions = [
            self.do_command(0, &commands[0]),
            self.do_command(1, &commands[1]),
        ];
        let next_positions = self.update_player_collisions(next_positions);
        self.update_player_travel(next_positions);

        self.status = if self.players[0].finished() && self.players[1].finished() {
            if self.players[0].speed > self.players[1].speed {
                GameStatus::PlayerOneWon
            } else if self.players[0].speed < self.players[1].speed {
                GameStatus::PlayerTwoWon
            } else {
                GameStatus::Draw
            }
        } else if self.players[0].finished() {
            GameStatus::PlayerOneWon
        } else if self.players[1].finished() {
            GameStatus::PlayerTwoWon
        } else {
            GameStatus::Continue
        };
    }

    pub fn reset_players_to_start(&mut self) {
        self.players[0].position = Position { x: 1, y: 1 };
        self.players[1].position = Position { x: 1, y: 4 };
        for player in &mut self.players {
            player.speed = 5;
            player.boost_remaining = 0;
            player.oils = 0;
            player.boosts = 0;
        }
    }

    fn do_command(&mut self, player_index: usize, command: &Command) -> Position {
        use Command::*;
        self.players[player_index].tick_boost();
        let mut next_y = self.players[player_index].position.y;

        match command {
            Nothing => {}
            Accelerate => self.players[player_index].accelerate(),
            Decelerate => self.players[player_index].decelerate(),
            TurnLeft => next_y = next_y.saturating_sub(1).max(MIN_Y),
            TurnRight => next_y = next_y.saturating_add(1).min(MAX_Y),
            UseBoost => self.players[player_index].boost(),
            UseOil => {
                debug_assert!(self.players[player_index].oils > 0);
                self.players[player_index].oils = self.players[player_index].oils.saturating_sub(1);
                let player_position = self.players[player_index].position;
                let mut obstacles = (*self.obstacles).clone();
                obstacles.insert(Position {
                    x: player_position.x.saturating_sub(1),
                    y: player_position.y,
                });
                self.obstacles = Rc::new(obstacles);
            }
        }

        let turning = match command {
            TurnLeft | TurnRight => true,
            _ => false,
        };

        let next_x = self.players[player_index].next_position_x(turning);
        Position {
            x: next_x,
            y: next_y,
        }
    }

    fn update_player_collisions(&mut self, next_positions: [Position; 2]) -> [Position; 2] {
        let same_lanes_before = self.players[0].position.y == self.players[1].position.y;
        let same_lanes_after = next_positions[0].y == next_positions[1].y;
        let first_passing_second = self.players[0].position.x < self.players[1].position.x
            && next_positions[0].x >= next_positions[1].x;
        let second_passing_first = self.players[1].position.x < self.players[0].position.x
            && next_positions[1].x >= next_positions[0].x;
        let same_x_after = next_positions[0].x == next_positions[1].x;

        if same_lanes_before && same_lanes_after && first_passing_second {
            [
                Position {
                    y: next_positions[0].y,
                    x: next_positions[1].x.saturating_sub(1),
                },
                next_positions[1],
            ]
        } else if same_lanes_before && same_lanes_after && second_passing_first {
            [
                next_positions[0],
                Position {
                    y: next_positions[1].y,
                    x: next_positions[0].x.saturating_sub(1),
                },
            ]
        } else if same_lanes_after && same_x_after {
            [
                Position {
                    y: self.players[0].position.y,
                    x: self.players[0].next_position_x(true),
                },
                Position {
                    y: self.players[1].position.y,
                    x: self.players[1].next_position_x(true),
                },
            ]
        } else {
            next_positions
        }
    }

    fn update_player_travel(&mut self, next_positions: [Position; 2]) {
        for (player, next_position) in self.players.iter_mut().zip(next_positions.iter()) {
            player.move_along(
                *next_position,
                &self.obstacles,
                &self.powerup_oils,
                &self.powerup_boosts,
            );
        }
    }

    pub fn valid_moves(&self, player_index: usize) -> Vec<Command> {
        let player = &self.players[player_index];
        let mut result = Vec::with_capacity(7);
        result.push(Command::Nothing);
        result.push(Command::Accelerate);
        if player.speed > SPEED_0 {
            result.push(Command::Decelerate);
        }
        if player.position.y > MIN_Y {
            result.push(Command::TurnLeft);
        }
        if player.position.y < MAX_Y - 1 {
            result.push(Command::TurnRight);
        }
        if player.boosts > 0 {
            result.push(Command::UseBoost);
        }
        if player.oils > 0 {
            result.push(Command::UseOil);
        }
        result
    }
}

impl Player {
    fn accelerate(&mut self) {
        self.speed = match self.speed {
            i if i < SPEED_1 => SPEED_1,
            i if i < SPEED_2 => SPEED_2,
            i if i < SPEED_3 => SPEED_3,
            SPEED_BOOST => SPEED_BOOST,
            _ => SPEED_4,
        };
    }

    fn decelerate(&mut self) {
        self.speed = match self.speed {
            i if i <= SPEED_1 => SPEED_0,
            i if i <= SPEED_2 => SPEED_1,
            i if i <= SPEED_3 => SPEED_2,
            i if i <= SPEED_4 => SPEED_3,
            _ => SPEED_4,
        };
        self.boost_remaining = 0;
    }

    fn decelerate_from_obstacle(&mut self) {
        self.speed = match self.speed {
            i if i <= SPEED_2 => SPEED_1,
            i if i <= SPEED_3 => SPEED_2,
            i if i <= SPEED_4 => SPEED_3,
            _ => SPEED_4,
        };
        self.boost_remaining = 0;
    }

    fn boost(&mut self) {
        debug_assert!(self.boosts > 0);
        self.speed = SPEED_BOOST;
        self.boost_remaining = BOOST_DURATION;
        self.boosts = self.boosts.saturating_sub(1);
    }

    fn tick_boost(&mut self) {
        self.boost_remaining = self.boost_remaining.saturating_sub(1);
        if self.boost_remaining == 0 && self.speed == SPEED_BOOST {
            self.speed = SPEED_4;
        }
    }

    fn next_position_x(&mut self, turning: bool) -> u16 {
        if turning {
            self.position.x.saturating_add(self.speed.saturating_sub(1))
        } else {
            self.position.x.saturating_add(self.speed)
        }
    }

    fn move_along(
        &mut self,
        next_position: Position,
        obstacles: &BTreeSet<Position>,
        powerup_oils: &BTreeSet<Position>,
        powerup_boosts: &BTreeSet<Position>,
    ) {
        let range = (
            Included(Position {
                y: next_position.y,
                x: self.position.x.saturating_add(1),
            }),
            Excluded(Position {
                y: next_position.y,
                x: next_position.x.saturating_add(1),
            }),
        );

        for _ in obstacles.range(range) {
            self.decelerate_from_obstacle();
        }
        self.oils = self
            .oils
            .saturating_add(powerup_oils.range(range).count() as u16);
        self.boosts = self
            .boosts
            .saturating_add(powerup_boosts.range(range).count() as u16);

        self.position = next_position;
    }

    fn finished(&self) -> bool {
        self.position.x >= WIDTH
    }
}