tetris/src/actors/mod.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

2020-04-05 23:36:00 +00:00
use crate::game::{Action, Controllable, Game};
2020-03-30 16:28:53 +00:00
use crate::playfield::{Matrix, PlayField};
use crate::tetromino::{Tetromino, TetrominoType};
2020-04-05 17:24:10 +00:00
use rand::rngs::SmallRng;
2020-03-30 16:28:53 +00:00
2020-04-05 23:36:00 +00:00
pub mod genetic;
2020-03-30 16:28:53 +00:00
pub mod qlearning;
2020-03-30 21:23:51 +00:00
#[derive(Hash, PartialEq, Eq, Clone, Debug)]
2020-03-30 16:28:53 +00:00
pub struct State {
matrix: Matrix,
active_piece: Option<Tetromino>,
held_piece: Option<TetrominoType>,
2020-04-05 20:34:33 +00:00
line_clears: u32,
2020-03-30 16:28:53 +00:00
}
impl From<Game> for State {
fn from(game: Game) -> Self {
(&game).into()
}
}
impl From<&Game> for State {
fn from(game: &Game) -> Self {
2020-04-05 20:34:33 +00:00
let mut state: State = game.playfield().clone().into();
state.line_clears = game.line_clears;
state
2020-03-30 16:28:53 +00:00
}
}
impl From<PlayField> for State {
fn from(playfield: PlayField) -> Self {
Self {
matrix: playfield.field().clone(),
active_piece: playfield.active_piece,
held_piece: playfield.hold_piece().map(|t| t.clone()),
2020-04-05 20:34:33 +00:00
line_clears: 0,
2020-03-30 16:28:53 +00:00
}
}
}
pub trait Actor {
2020-04-06 03:39:19 +00:00
fn get_action(&self, rng: &mut SmallRng, game: &Game, legal_actions: &[Action]) -> Action;
2020-03-30 21:23:51 +00:00
fn dbg(&self);
2020-03-30 16:28:53 +00:00
}
2020-04-05 23:36:00 +00:00
pub trait Predictable {
fn get_next_state(&self, action: Action) -> Self;
}
impl Predictable for Game {
/// Expensive, performs a full clone.
fn get_next_state(&self, action: Action) -> Self {
let mut game = self.clone();
match action {
Action::Nothing => (),
Action::MoveLeft => game.move_left(),
Action::MoveRight => game.move_right(),
Action::SoftDrop => game.move_down(),
Action::HardDrop => game.hard_drop(),
Action::Hold => game.hold(),
Action::RotateLeft => game.rotate_left(),
Action::RotateRight => game.rotate_right(),
};
game
}
}
2020-04-06 03:39:19 +00:00
pub fn apply_action_to_game(action: Action, game: &mut Game) {
match action {
Action::Nothing => (),
Action::MoveLeft => game.move_left(),
Action::MoveRight => game.move_right(),
Action::SoftDrop => game.move_down(),
Action::HardDrop => game.hard_drop(),
Action::Hold => game.hold(),
Action::RotateLeft => game.rotate_left(),
Action::RotateRight => game.rotate_right(),
}
}