From da1153b4164e670f95ef8014ba7156ac2c2a3489 Mon Sep 17 00:00:00 2001 From: ND Tai Date: Mon, 18 Oct 2021 11:32:17 +0700 Subject: [PATCH] init --- .github/workflows/ci.yaml | 57 ++++++++ .vscode/settings.json | 5 + Cargo.lock | 225 ++++++++++++++++++++++++++++++ Cargo.toml | 15 ++ readme.md | 22 +++ resources/maps/map00 | 9 ++ src/a_star.rs | 82 +++++++++++ src/dfs.rs | 43 ++++++ src/lib.rs | 281 ++++++++++++++++++++++++++++++++++++++ src/main.rs | 3 - src/manual.rs | 38 ++++++ 11 files changed, 777 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/ci.yaml create mode 100644 .vscode/settings.json create mode 100644 resources/maps/map00 create mode 100644 src/a_star.rs create mode 100644 src/dfs.rs create mode 100644 src/lib.rs delete mode 100644 src/main.rs create mode 100644 src/manual.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..b2b3b0c --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,57 @@ +name: sokoban + +on: + push: + tags: + - '*' + +env: + CARGO_TERM_COLOR: always + +jobs: + publish: + name: Publish for ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + name: [linux, windows, macos] + + include: + - name: linux + os: ubuntu-latest + suffix: "" + asset_suffix: -linux + - name: windows + os: windows-latest + suffix: .exe + asset_suffix: -windows.exe + - name: macos + os: macos-latest + suffix: "" + asset_suffix: -macos + + steps: + - uses: actions/checkout@v2 + - name: Build + run: cargo build --release --all + - name: Upload a* binaries + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/astar${{ matrix.suffix }} + asset_name: astar${{ matrix.asset_suffix }} + tag: ${{github.ref}} + - name: Upload manual binaries + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/manual${{ matrix.suffix }} + asset_name: manual${{ matrix.asset_suffix }} + tag: ${{github.ref}} + - name: Upload dfs binaries + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/dfs${{ matrix.suffix }} + asset_name: dfs${{ matrix.asset_suffix }} + tag: ${{github.ref}} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2e32934 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "cSpell.words": [ + "sokoban" + ] +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 3bc9805..5ccfa6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,231 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "crossterm" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "486d44227f71a1ef39554c0dc47e44b9f4139927c75043312690c3f476d1d788" +dependencies = [ + "bitflags", + "crossterm_winapi", + "libc", + "mio", + "parking_lot", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a6966607622438301997d3dac0d2f6e9a90c68bb6bc1785ea98456ab93c0507" +dependencies = [ + "winapi", +] + +[[package]] +name = "either" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" + +[[package]] +name = "instant" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "716d3d89f35ac6a34fd0eed635395f4c3b76fa889338a4632e5231a8684216bd" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "itertools" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" +dependencies = [ + "either", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6" + +[[package]] +name = "lock_api" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "mio" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c2bdb6314ec10835cd3293dd268473a835c02b7b352e788be788b3c6ca6bb16" +dependencies = [ + "libc", + "log", + "miow", + "ntapi", + "winapi", +] + +[[package]] +name = "miow" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" +dependencies = [ + "winapi", +] + +[[package]] +name = "ntapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" +dependencies = [ + "winapi", +] + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall", + "smallvec", + "winapi", +] + +[[package]] +name = "redox_syscall" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" +dependencies = [ + "bitflags", +] + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "signal-hook" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c98891d737e271a2954825ef19e46bd16bdb98e2746f2eec4f7a4ef7946efd1" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fd5867f1c4f2c5be079aee7a2adf1152ebb04a4bc4d341f504b7dece607ed4" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +dependencies = [ + "libc", +] + +[[package]] +name = "smallvec" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ecab6c735a6bb4139c0caafd0cc3635748bbb3acf4550e8138122099251f309" + [[package]] name = "sokoban" version = "0.1.0" +dependencies = [ + "crossterm", + "itertools", + "lazy_static", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml index 9d5f4ce..1882dd0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,18 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +crossterm = "*" +itertools = "*" +lazy_static = "*" + +[[bin]] +name = "manual" +path = "src/manual.rs" + +[[bin]] +name = "dfs" +path = "src/dfs.rs" + +[[bin]] +name = "astar" +path = "src/a_star.rs" \ No newline at end of file diff --git a/readme.md b/readme.md index e69de29..a96c3d1 100644 --- a/readme.md +++ b/readme.md @@ -0,0 +1,22 @@ +### Luật chơi được chuyển đổi sang hướng *programable*: +* Các đối tượng W(wall), P(player), E(empty), ET(empty-target), B(box), BT(boxed-target) +* Số box bằng với số target, game mặc định là solvable +* Player chỉ có thể di chuyển bằng các hành động move (ML-MR-MU-MD), push (PL-PR-PU-PD) +* Box chỉ có thể di chuyển khi chịu tác động của Player +* Box chỉ có thể di chuyển đến các vị trí E hoặc ET lân cận +* Khi một box được di chuyển đến vị trí ET nó trở thành BT, ngược lại nếu box bị di chuyển ra khỏi BT nó trở thành ET +* Player chỉ có thể di chuyển: + - đến các vị trí E hoặc ET + - các vị trí của box phía trước (B, BT) nếu box đó có thể tịnh tiến theo hướng từ player -> box +* Khi player di chuyển đến vị trí của một box thì box đó đồng thời tiến về phía trước cùng chiều với player (bị đẩy) +* Người chơi thua khi có ít nhất 1 box (B not BT) không thể di chuyển +* Người chơi thắng khi tất cả các target(ET) được 'đóng lại' (trở thành BT - boxed-target) + +### Tóm tắt bài toán: +- Đầu vào là một *map* chứa vị trí của wall, player, empty, target, box +- Mỗi hành động di chuyển của người chơi được xem là một step - 1 node của cây hành động, chúng ta cần tìm tập các step phù hợp để biến đổi map ban đầu sang map có trạng thái win + +### Phân tích, thiết kế giải thuật: +- Dễ thấy kể cả những game 'dễ' cũng cần từ 30-40 bước di chuyển để hoàn thành trong điều kiện tốt nhất -> khi đó ta cần xét tối đa 4^30 ~1.15e18 trường hợp -> sử dụng DFS nhằm tránh tràn bộ nhớ, thay vì lưu lại toàn bộ map với mỗi step ta tạo ra các bước undo với mỗi loại hành động của 'player' +- Nếu người chơi ML rồi sau đó MR (hoặc MU-MD, MR-ML ...) thì game lại trở về trạng thái ban đầu -> sử dụng biện pháp cắt cạnh để giảm những trường hợp này khi backtracking +- Các hành động move sẽ không làm thay đổi trạng thái của game, do đó thay vì di chuyển một cách 'ngẫu nhiên' cho đến khi tìm được phương án phù hợp ta chỉ quan tâm đến các bước push diff --git a/resources/maps/map00 b/resources/maps/map00 new file mode 100644 index 0000000..f31e673 --- /dev/null +++ b/resources/maps/map00 @@ -0,0 +1,9 @@ +1 1 +3 2 +0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 0 1 1 1 1 0 +0 1 1 1 1 1 1 1 1 1 0 +0 1 1 1 0 0 0 0 1 1 0 +0 0 1 0 0 0 0 0 1 1 0 +0 0 1 1 1 1 1 2 1 1 0 +0 0 0 0 0 0 0 0 0 0 0 \ No newline at end of file diff --git a/src/a_star.rs b/src/a_star.rs new file mode 100644 index 0000000..93bb34b --- /dev/null +++ b/src/a_star.rs @@ -0,0 +1,82 @@ +use sokoban::{Actions::*, Directions::*, *}; +use std::{collections::BinaryHeap, thread, time::Duration}; + +fn heuristic(game: &GameBoard) -> usize { + // a simple heuristic define by sum of minimal manhattan distance of box - target + game.targets + .iter() + .map(|&(tx, ty)| { + game.boxes + .iter() + .map(|&(bx, by)| { + let dx = if tx > bx { tx - bx } else { bx - tx }; + let dy = if ty > by { ty - by } else { by - ty }; + dx + dy + }) + .min() + .unwrap() + }) + .sum() +} + +#[derive(Debug, PartialEq, Eq)] +struct State { + pub perdict_cost: usize, + pub game: GameBoard, +} + +impl PartialOrd for State { + fn partial_cmp(&self, other: &Self) -> Option { + other.perdict_cost.partial_cmp(&self.perdict_cost) + } +} + +impl Ord for State { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.perdict_cost.cmp(&self.perdict_cost) + } +} + +fn a_star(game: &mut GameBoard) -> Option { + let mut queue = BinaryHeap::new(); + queue.push(State { + perdict_cost: heuristic(&game) + game.actions.len(), + game: game.clone() + }); + + while !queue.is_empty() { + let game = queue.pop().unwrap().game; + game.render(); + thread::sleep(Duration::from_millis(50)); + for d in DIRECTIONS { + if let Some(Move(last)) = game.actions.last() { + if matches!( + (last, &d), + (Left, Right) | (Right, Left) | (Up, Down) | (Down, Up) + ) { + continue; + } + } + let mut game = game.clone(); + if game.move_(&d).is_none() { + continue; + }; + if game.is_win() { + return Some(game); + } + queue.push(State { + perdict_cost: heuristic(&game) + game.actions.len(), + game: game.clone() + }); + } + } + None +} + +fn main() { + let src = include_str!("../resources/maps/map00"); + let mut game = GameBoard::from_src(src); + if let Some(game) = a_star(&mut game) { + game.render(); + }; +} diff --git a/src/dfs.rs b/src/dfs.rs new file mode 100644 index 0000000..c214df6 --- /dev/null +++ b/src/dfs.rs @@ -0,0 +1,43 @@ +use sokoban::{Actions::*, Directions::*, *}; +use std::{thread, time::Duration}; + +fn dfs(game: &mut GameBoard, max_deep: usize) -> bool { + if game.is_win() { + return true; + } + if game.actions.len() >= max_deep { + return false; + } + for d in DIRECTIONS { + if let Some(Move(last)) = game.actions.last() { + if matches!( + (last, &d), + (Left, Right) | (Right, Left) | (Up, Down) | (Down, Up) + ) { + continue; + } + } + if game.move_(&d).is_none() { + continue; + }; + thread::sleep(Duration::from_millis(50)); + game.render(); + if dfs(game, max_deep) { + return true; + } + game.undo(); + } + false +} + +fn main() { + let src = include_str!("../resources/maps/map00"); + let mut game = GameBoard::from_src(src); + for i in 14..50 { + if dfs(&mut game, i) { + game.render(); + println!("You win!"); + break; + } + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..1b2f413 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,281 @@ +use std::fmt::Display; + +use crossterm::{cursor, execute, terminal::{Clear, ClearType, disable_raw_mode, enable_raw_mode}}; +use itertools::Itertools; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Entities { + Wall, + Road, + Target, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Directions { + Left, + Right, + Up, + Down, +} + +pub const DIRECTIONS: [Directions; 4] = [ + Directions::Left, + Directions::Right, + Directions::Up, + Directions::Down, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Actions { + Move(Directions), + Push(Directions), +} + +impl Display for Actions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Actions::Move(Directions::Left) => write!(f, "ML"), + Actions::Move(Directions::Right) => write!(f, "MR"), + Actions::Move(Directions::Up) => write!(f, "MU"), + Actions::Move(Directions::Down) => write!(f, "MD"), + Actions::Push(Directions::Left) => write!(f, "PL"), + Actions::Push(Directions::Right) => write!(f, "PR"), + Actions::Push(Directions::Up) => write!(f, "PU"), + Actions::Push(Directions::Down) => write!(f, "PD"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GameBoard { + map: Vec>, + player: (usize, usize), + pub targets: Vec<(usize, usize)>, + pub boxes: Vec<(usize, usize)>, + pub actions: Vec, +} + +impl GameBoard { + pub fn from_src(source: &str) -> GameBoard { + let mut lines = source.split('\n'); + let to_vec = |src: &str| { + src.split_whitespace() + .map(|i| i.parse().unwrap()) + .collect_vec() + }; + let first_line = to_vec(lines.next().unwrap()); + let boxes = to_vec(lines.next().unwrap()).into_iter().tuples().collect(); + let map: Vec> = lines + .map(|line| { + line.split_whitespace() + .map(|i| match i { + "0" => Entities::Wall, + "1" => Entities::Road, + "2" => Entities::Target, + _ => unreachable!(), + }) + .collect() + }) + .collect(); + + let mut targets = vec![]; + for y in 0..map.len() { + for x in 0..map[0].len() { + if matches!(map[y][x], Entities::Target) { + targets.push((x, y)); + } + } + } + + GameBoard { + map, + boxes, + targets, + player: (first_line[0], first_line[1]), + actions: vec![], + } + } + + fn stringify(&self) -> String { + let mut result = vec![]; + for y in 0..self.height() { + let mut line = vec![]; + for x in 0..self.width() { + line.push(match self.map[y][x] { + Entities::Wall => "⬛", + _ if self.player == (x, y) => "🐱", + Entities::Road => { + if self.boxes.contains(&(x, y)) { + "🔴" + } else { + " " + } + } + Entities::Target => { + if self.boxes.contains(&(x, y)) { + "🔘" + } else { + "[]" + } + } + }); + } + result.push(line.join("")) + } + result.join("\n\r") + } + + fn width(&self) -> usize { + self.map[0].len() + } + + fn height(&self) -> usize { + self.map.len() + } + + fn is_free(&self, x: usize, y: usize) -> bool { + !matches!(self.map[y][x], Entities::Wall) && !self.boxes.contains(&(x, y)) + } + + fn set_player_position(&mut self, x: usize, y: usize) { + self.player = (x, y); + } + + fn move_box(&mut self, src: (usize, usize), dst: (usize, usize)) { + let pos = self.boxes.iter().position(|&b| b == src).unwrap(); + let _ = std::mem::replace(&mut self.boxes[pos], dst); + } + + fn _move(&mut self, direction: &Directions) -> Option { + let (px, py) = self.player; + match direction { + Directions::Left => { + if px < 1 || matches!(self.map[py][px - 1], Entities::Wall) { + return None; + } + if !self.boxes.contains(&(px - 1, py)) { + self.set_player_position(px - 1, py); + return Some(Actions::Move(*direction)); + } + if px < 2 || !self.is_free(px - 2, py) { + return None; + } + self.set_player_position(px - 1, py); + self.move_box((px - 1, py), (px - 2, py)); + Some(Actions::Push(*direction)) + } + Directions::Right => { + if px + 1 >= self.width() || matches!(self.map[py][px + 1], Entities::Wall) { + return None; + } + if !self.boxes.contains(&(px + 1, py)) { + self.set_player_position(px + 1, py); + return Some(Actions::Move(*direction)); + } + if px + 2 >= self.width() || !self.is_free(px + 2, py) { + return None; + } + self.set_player_position(px + 1, py); + self.move_box((px + 1, py), (px + 2, py)); + Some(Actions::Push(*direction)) + } + Directions::Up => { + if py < 1 || matches!(self.map[py - 1][px], Entities::Wall) { + return None; + } + if !self.boxes.contains(&(px, py - 1)) { + self.set_player_position(px, py - 1); + return Some(Actions::Move(*direction)); + } + if py < 2 || !self.is_free(px, py - 2) { + return None; + } + self.set_player_position(px, py - 1); + self.move_box((px, py - 1), (px, py - 2)); + Some(Actions::Push(*direction)) + } + Directions::Down => { + if py + 1 >= self.height() || matches!(self.map[py + 1][px], Entities::Wall) { + return None; + } + if !self.boxes.contains(&(px, py + 1)) { + self.set_player_position(px, py + 1); + return Some(Actions::Move(*direction)); + } + if py + 2 >= self.height() || !self.is_free(px, py + 2) { + return None; + } + self.set_player_position(px, py + 1); + self.move_box((px, py + 1), (px, py + 2)); + Some(Actions::Push(*direction)) + } + } + } + + pub fn is_win(&self) -> bool { + self.boxes + .iter() + .all(|&(x, y)| matches!(self.map[y][x], Entities::Target)) + } + + pub fn move_(&mut self, direction: &Directions) -> Option { + let result = self._move(direction); + if let Some(res) = result { + self.actions.push(res); + } + result + } + + pub fn render(&self) { + let mut stdout = std::io::stdout(); + enable_raw_mode().unwrap(); + execute!(stdout, Clear(ClearType::All), cursor::MoveTo(0, 0)).unwrap(); + println!("{}", self.stringify()); + println!( + "\rHistory: {}\r", + self.actions.iter().map(|i| i.to_string()).join(" ") + ); + println!("\rSteps: {}", self.actions.len()); + disable_raw_mode().unwrap(); + } + + pub fn undo(&mut self) { + if let Some(act) = self.actions.pop() { + let (px, py) = self.player; + match act { + Actions::Move(Directions::Left) => self.set_player_position(px + 1, py), + Actions::Move(Directions::Right) => self.set_player_position(px - 1, py), + Actions::Move(Directions::Up) => self.set_player_position(px, py + 1), + Actions::Move(Directions::Down) => self.set_player_position(px, py - 1), + Actions::Push(Directions::Left) => { + self.set_player_position(px + 1, py); + self.move_box((px - 1, py), (px, py)); + } + Actions::Push(Directions::Right) => { + self.set_player_position(px - 1, py); + self.move_box((px + 1, py), (px, py)); + } + Actions::Push(Directions::Up) => { + self.set_player_position(px, py + 1); + self.move_box((px, py - 1), (px, py)); + } + Actions::Push(Directions::Down) => { + self.set_player_position(px, py - 1); + self.move_box((px, py + 1), (px, py)); + } + } + } + } + + // pub fn targets(&self) -> Vec<(usize, usize)> { + // let mut result = vec![]; + // for y in 0..self.height() { + // for x in 0..self.width() { + // if matches!(self.map[y][x], Entities::Target) { + // result.push((x, y)); + // } + // } + // } + // result + // } +} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index e7a11a9..0000000 --- a/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello, world!"); -} diff --git a/src/manual.rs b/src/manual.rs new file mode 100644 index 0000000..bc5d7ee --- /dev/null +++ b/src/manual.rs @@ -0,0 +1,38 @@ +use crossterm::{event::{read, Event, KeyCode, KeyEvent, KeyModifiers}, terminal::{disable_raw_mode, enable_raw_mode}}; +use sokoban::*; + +fn main() { + let src = include_str!("../resources/maps/map00"); + let mut game = GameBoard::from_src(src); + loop { + game.render(); + if game.is_win() { + break; + } + enable_raw_mode().unwrap(); + let direction = match read().unwrap() { + Event::Key(KeyEvent { + code, + modifiers: KeyModifiers::NONE, + }) => match code { + KeyCode::Char('q') => { + println!("Quit!"); + return; + } + KeyCode::Char('u') => { + game.undo(); + continue; + } + KeyCode::Left => Directions::Left, + KeyCode::Right => Directions::Right, + KeyCode::Up => Directions::Up, + KeyCode::Down => Directions::Down, + _ => continue, + }, + _ => continue, + }; + disable_raw_mode().unwrap(); + game.move_(&direction); + } + println!("\rYou win!"); +}