wip using macroquad

This commit is contained in:
Michael Zhang 2024-01-25 19:41:47 -06:00
parent 9c694b5688
commit e64baa2607
26 changed files with 1627 additions and 2045 deletions

2
.envrc
View file

@ -1 +1 @@
use flake
# use flake

7
.gitignore vendored
View file

@ -3,6 +3,13 @@
.direnv
# Added by cargo
#
# already existing elements were commented out
#/target
# Added by cargo
#
# already existing elements were commented out

2006
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -3,17 +3,11 @@ name = "wedge"
version = "0.1.0"
edition = "2021"
[workspace]
members = ["run-wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
env_logger = "0.10.0"
pollster = "0.2.5"
wgpu = { version = "0.14.2", features = ["webgl"] }
winit = "0.27.5"
# wasm
console_error_panic_hook = "0.1.7"
console_log = "0.2.0"
wasm-bindgen-futures = "0.4.33"
web-sys = "0.3.60"
anyhow = "1.0.79"
json5 = "0.4.1"
macroquad = "0.4.4"
serde = { version = "1.0.195", features = ["derive"] }
serde_json = "1.0.111"

View file

@ -1,14 +0,0 @@
fn main() {
// if cfg!(target_os = "linux") {
// for path in env!("LD_LIBRARY_PATH").split(":") {
// println!(r"cargo:rustc-link-search={}", path);
// }
// println!("cargo:rustc-link-lib=X11");
// println!("cargo:rustc-link-lib=Xcursor");
// println!("cargo:rustc-link-lib=Xrandr");
// println!("cargo:rustc-link-lib=Xi");
// println!("cargo:rustc-link-lib=vulkan");
// }
}

View file

@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1672554122,
"narHash": "sha256-vTnoOiRQtjaqdW0Hmtz73GyWEcyQstifpoZ7QAscWyA=",
"lastModified": 1706163833,
"narHash": "sha256-Vw+jTVtKceT+ScaIn7tHy8JjRZZpmg2fAdoInLAsW/M=",
"owner": "nix-community",
"repo": "fenix",
"rev": "f62d27fa582511fe4d1c32855b8cb4c57e335d9d",
"rev": "043f63f55e9c9b808852ea82edee1f2a1af37e91",
"type": "github"
},
"original": {
@ -22,12 +22,15 @@
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1667395993,
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
"lastModified": 1705309234,
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
@ -37,11 +40,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1667629849,
"narHash": "sha256-P+v+nDOFWicM4wziFK9S/ajF2lc0N2Rg9p6Y35uMoZI=",
"owner": "nixos",
"lastModified": 1706006310,
"narHash": "sha256-nDPz0fj0IFcDhSTlXBU2aixcnGs2Jm4Zcuoj0QtmiXQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "3bacde6273b09a21a8ccfba15586fb165078fb62",
"rev": "b43bb235efeab5324c5e486882ef46749188eee2",
"type": "github"
},
"original": {
@ -59,11 +62,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1672498287,
"narHash": "sha256-K2ywmLEJ32D0vtmMHmRUymX2FmHi+kklyLYYcyCV5QY=",
"lastModified": 1706106882,
"narHash": "sha256-31DivWu0cC50gR2CgbGtLCf77nuiw4kdiI7B8ioqzLw=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "f31733b1d61dd8ab2012bbe466838be244a96dd3",
"rev": "0d52934d19d7addcafcfda92a1d547b51556beec",
"type": "github"
},
"original": {
@ -72,6 +75,21 @@
"repo": "rust-analyzer",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",

View file

@ -14,15 +14,16 @@
overlays = [ fenix.overlays.default ];
};
rustc = pkgs.fenix.default.rustc;
cargo = pkgs.fenix.default.cargo;
rustc = pkgs.fenix.stable.rustc;
cargo = pkgs.fenix.stable.cargo;
neededLibs = with pkgs;
(with xorg; [ libX11 libXcursor libXrandr libXi ])
++ [ vulkan-loader wayland wayland-protocols libxkbcommon ];
(with xorg; [ ])
++ [ ];
flakePkgs = { wedge = pkgs.callPackage ./. { inherit rustc cargo; }; };
in rec {
in
rec {
packages = flake-utils.lib.flattenTree flakePkgs;
defaultPackage = packages.wedge;
@ -36,27 +37,27 @@
'';
packages = (with pkgs; [
cargo-watch
cargo-deny
cargo-edit
sqlx-cli
sqlite
wasm-pack
# cargo-watch
# cargo-deny
# cargo-edit
# sqlx-cli
# sqlite
(with pkgs.fenix;
combine [
rustc
cargo
targets.wasm32-unknown-unknown.latest.rust-std
])
combine [
rustc
cargo
# targets.wasm32-unknown-unknown.latest.rust-std
])
]);
PKG_CONFIG_PATH = with pkgs;
lib.concatStringsSep ":" [
"${fontconfig.dev}/lib/pkgconfig"
"${xorg.libX11.dev}/lib/pkgconfig"
"${xorg.libXcursor.dev}/lib/pkgconfig"
"${xorg.libXi.dev}/lib/pkgconfig"
"${xorg.libXrandr.dev}/lib/pkgconfig"
# "${fontconfig.dev}/lib/pkgconfig"
# "${xorg.libX11.dev}/lib/pkgconfig"
# "${xorg.libXcursor.dev}/lib/pkgconfig"
# "${xorg.libXi.dev}/lib/pkgconfig"
# "${xorg.libXrandr.dev}/lib/pkgconfig"
];
};
});

124
levels/level1.json Normal file
View file

@ -0,0 +1,124 @@
{
"dimensions": [8, 8],
"player1": {
"position": [5, 5],
"color": [66, 134, 244],
},
"player2": {
"position": [5, 5],
"color": [244, 83, 65],
},
"goal1": [0, 0],
"goal2": [0, 0],
"blocks": [
{
"movable": true,
"orientation": 2,
"color": [255, 10, 100],
"segments": [
[6, 4, 2, 0],
[6, 5, 0, 0],
],
},
{
"movable": true,
"orientation": 1,
"color": [0, 255, 100],
"segments": [
[4, 3, 2, 0],
[5, 3, 0, 0],
[6, 3, 4, 0],
[4, 3, 2, 1],
[5, 3, 0, 1],
[6, 3, 4, 1],
],
},
{
"movable": true,
"orientation": 2,
"color": [20, 25, 100],
"segments": [
[6, 2, 4, 0],
[6, 1, 0, 0],
[6, 2, 4, 1],
[6, 1, 0, 1],
],
},
{
"movable": true,
"orientation": 1,
"color": [110, 30, 230],
"segments": [
[3, 5, 4, 0],
[2, 5, 0, 0],
[1, 5, 0, 0],
[3, 5, 4, 1],
[2, 5, 0, 1],
[1, 5, 0, 1],
],
},
{
"movable": true,
"orientation": 2,
"color": [240, 50, 60],
"segments": [
[3, 5, 2, 0],
[3, 6, 0, 0],
],
},
{
"movable": true,
"orientation": 2,
"color": [120, 220, 20],
"segments": [
[3, 3, 4, 1],
[3, 2, 0, 1],
],
},
{
"movable": false,
"orientation": 0,
"color": [0, 0, 0],
"segments": [
[2, 0, 0, 0],
[2, 1, 0, 0],
[2, 2, 0, 0],
[2, 3, 0, 0],
[2, 0, 0, 1],
[2, 1, 0, 1],
[2, 2, 0, 1],
[2, 3, 0, 1],
],
},
{
"movable": false,
"orientation": 0,
"color": [0, 0, 0],
"segments": [
[4, 4, 0, 0],
[4, 5, 0, 0],
[4, 6, 0, 0],
[4, 7, 0, 0],
[4, 4, 0, 1],
[4, 5, 0, 1],
[4, 6, 0, 1],
[4, 7, 0, 1],
],
},
{
"movable": false,
"orientation": 0,
"color": [0, 0, 0],
"segments": [
[7, 4, 0, 0],
[7, 5, 0, 0],
[7, 6, 0, 0],
[7, 7, 0, 0],
[7, 4, 0, 1],
[7, 5, 0, 1],
[7, 6, 0, 1],
[7, 7, 0, 1],
],
},
],
}

67
levels/tutorial.json Normal file
View file

@ -0,0 +1,67 @@
{
"dimensions": [3, 7],
"player1": {
"position": [1, 6],
"color": [66, 134, 244],
},
"player2": {
"position": [1, 6],
"color": [244, 83, 65],
},
"goal1": [1, 0],
"goal2": [1, 0],
"blocks": [
{
"movable": true,
"orientation": 1,
"color": [255, 10, 100],
"segments": [
[1, 3, 0, 0],
[2, 3, 4, 0],
],
},
{
"movable": true,
"orientation": 2,
"color": [105, 210, 50],
"segments": [
[2, 4, 2, 0],
[2, 5, 0, 0],
],
},
{
"movable": true,
"orientation": 2,
"color": [35, 150, 100],
"segments": [
[0, 4, 1, 1],
[0, 5, 0, 1],
],
},
{
"movable": true,
"orientation": 1,
"color": [25, 120, 10],
"segments": [
[0, 3, 3, 1],
[1, 3, 0, 1],
],
},
{
"movable": false,
"orientation": 0,
"color": [15, 15, 15],
"segments": [
[0, 2, 0, 0],
],
},
{
"movable": false,
"orientation": 0,
"color": [15, 15, 15],
"segments": [
[2, 2, 0, 1],
],
},
]
}

54
levels/tutorial2.json Normal file
View file

@ -0,0 +1,54 @@
{
"dimensions": [4, 8],
"player1": {
"position": [1, 7],
"color": [66, 134, 244],
},
"player2": {
"position": [1, 7],
"color": [244, 83, 65],
},
"goal1": [0, 0],
"goal2": [3, 0],
"blocks": [
{
"movable": false,
"orientation": 1,
"color": [0, 0, 0],
"segments": [
[0, 2, 0, 0],
[3, 2, 0, 0],
[0, 4, 0, 0],
[3, 4, 0, 0],
[3, 6, 0, 0],
[0, 2, 0, 1],
[3, 2, 0, 1],
[0, 4, 0, 1],
[0, 6, 0, 1],
[3, 6, 0, 1],
],
},
{
"movable": true,
"orientation": 1,
"color": [255, 10, 100],
"segments": [
[1, 5, 0, 0],
[2, 5, 4, 0],
[1, 5, 0, 1],
[2, 5, 4, 1],
],
},
{
"movable": true,
"orientation": 1,
"color": [10, 255, 100],
"segments": [
[1, 3, 3, 0],
[2, 3, 0, 0],
[1, 3, 3, 1],
[2, 3, 0, 1],
],
},
],
}

View file

@ -1,7 +0,0 @@
[package]
name = "run-wasm"
version = "0.1.0"
edition = "2021"
[dependencies]
cargo-run-wasm = "0.3.0"

View file

@ -1,3 +0,0 @@
fn main() {
cargo_run_wasm::run_wasm_with_css("body { margin: 0px; }");
}

4
rustfmt.toml Normal file
View file

@ -0,0 +1,4 @@
max_width = 80
tab_spaces = 2
wrap_comments = true
fn_single_line = true

116
src/animations.rs Normal file
View file

@ -0,0 +1,116 @@
use std::collections::{HashMap, HashSet};
use std::time::Duration;
use crate::game_state::level::{ChangeSet, Entity, FailSet};
use crate::game_state::Board;
pub type MoveResult = Result<ChangeSet, FailSet>;
pub type BlockOffsets = HashMap<Entity, (f32, f32)>;
// TODO: don't yeet around a HashMap all the time
pub type AnimationFn =
Box<dyn Fn(MoveResult, BlockOffsets, f32) -> BlockOffsets>;
// in seconds
const ANIMATION_DURATION: f32 = 1.0 / 6.0;
#[derive(Default)]
pub struct AnimationState {
pub is_animating: bool,
pub last_move_result: Option<MoveResult>,
pub progress: f32,
pub block_offsets: BlockOffsets,
pub immovable_blocks: HashSet<usize>,
progress_function: Option<AnimationFn>,
}
impl AnimationState {
pub fn new() -> Self {
AnimationState {
is_animating: false,
last_move_result: None,
progress: 0.0,
block_offsets: BlockOffsets::new(),
immovable_blocks: HashSet::new(),
progress_function: None,
}
}
pub fn begin_move_transition(&mut self, result: MoveResult) {
println!("result: {:?}", result);
self.last_move_result = Some(result);
self.is_animating = true;
self.progress = 0.0;
let func = |last_move_result: MoveResult,
mut offsets: BlockOffsets,
progress: f32| {
use std::f32::consts::PI;
match last_move_result {
// transition
Ok(change_set) => {
for (entity, direction) in change_set {
// TODO: implement ease-out?
let pair = direction.as_pair();
// cap progress at 1.0, we don't want blocks going past where they're supposed to
let progress = progress.min(1.0);
let offset = (pair.0 as f32 * progress, pair.1 as f32 * progress);
offsets.insert(entity, offset);
}
}
// vibrate all blocking pieces
Err(fail_set) => {
for index in fail_set {
let delta = 0.05 * (4.0 * PI * progress).sin() / (progress + 0.5);
offsets.insert(Entity::Block(index), (delta, delta));
}
}
}
offsets
};
self.progress_function = Some(Box::new(func));
}
pub fn make_progress(&mut self, delta: Duration) {
let progress =
self.progress + (delta.as_millis() as f32 / ANIMATION_DURATION) / 1000.0;
let block_offsets = if let Some(f) = &self.progress_function {
Some(f(
self.last_move_result.clone().unwrap(),
self.block_offsets.clone(),
progress,
))
} else {
None
};
// this should always work
if let Some(block_offsets) = block_offsets {
self.block_offsets = block_offsets;
self.progress = progress;
}
if self.progress > 1.0 {
self.is_animating = false;
self.block_offsets = BlockOffsets::new();
}
}
pub fn get_block_offset(&self, index: usize) -> (f32, f32) {
self
.block_offsets
.get(&Entity::Block(index))
.cloned()
.unwrap_or_else(|| (0.0, 0.0))
}
pub fn get_player_offset(&self, board: Board) -> (f32, f32) {
self
.block_offsets
.get(&Entity::Player(board))
.cloned()
.unwrap_or_else(|| (0.0, 0.0))
}
}

1
src/draw.rs Normal file
View file

@ -0,0 +1 @@
pub fn draw() {}

35
src/game_state/block.rs Normal file
View file

@ -0,0 +1,35 @@
use super::{BlockData, Color, Orientation, SegmentState};
#[derive(Clone, Debug)]
pub struct BlockState {
pub index: usize,
pub movable: bool,
pub color: Color,
pub orientation: Orientation,
pub segments: Vec<SegmentState>,
}
impl BlockState {
pub fn from_data(index: usize, data: &BlockData) -> Self {
let movable = data.movable;
let segments = data
.segments
.iter()
.map(|segment| SegmentState {
position: (segment[0], segment[1]),
shape: segment[2].into(),
board: segment[3].into(),
})
.collect();
let orientation = data.orientation.into();
let color = Color(data.color.0, data.color.1, data.color.2);
BlockState {
index,
movable,
color,
segments,
orientation,
}
}
}

48
src/game_state/level.rs Normal file
View file

@ -0,0 +1,48 @@
use std::collections::{HashMap, HashSet};
use super::{Board, LevelState, PushDir, Shape};
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Entity {
Block(usize),
Player(Board),
}
pub type ChangeSet = HashMap<Entity, PushDir>;
pub type FailSet = HashSet<usize>;
impl LevelState {
pub fn apply_change_set(&mut self, change_set: ChangeSet) {
for (entity, direction) in change_set {
let direction = direction.as_pair();
match entity {
Entity::Player(board) => {
let player = match board {
Board::Left => &mut self.player1_position,
Board::Right => &mut self.player2_position,
};
player.0 += direction.0;
player.1 += direction.1;
}
Entity::Block(index) => {
let block = self.blocks.get_mut(index).expect("big failure");
for segment in &mut block.segments {
segment.position.0 += direction.0;
segment.position.1 += direction.1;
}
}
}
}
}
pub fn try_move(
&mut self,
board: Board,
direction: PushDir,
) -> Result<ChangeSet, FailSet> {
let mut change_set = ChangeSet::default();
change_set.insert(Entity::Player(board), direction);
self.player_can_move(board, direction, change_set)
}
}

197
src/game_state/mod.rs Normal file
View file

@ -0,0 +1,197 @@
pub mod block;
pub mod level;
pub mod move_rules;
pub mod render;
use std::ops::Add;
use anyhow::Result;
use macroquad::color::Color as MQColor;
use self::block::BlockState;
#[derive(Debug)]
pub struct LevelState {
pub data: LevelData,
pub blocks: Vec<BlockState>,
pub player1_position: (i32, i32),
pub player2_position: (i32, i32),
}
#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
pub struct SegmentState {
position: (i32, i32),
shape: Shape,
board: Board,
}
impl LevelState {
pub fn new(data: LevelData) -> Self {
let blocks = data
.blocks
.iter()
.enumerate()
.map(|(i, block)| BlockState::from_data(i, block))
.collect();
LevelState {
blocks,
player1_position: data.player1.position,
player2_position: data.player2.position,
data,
}
}
pub fn check_win_condition(&self) -> bool {
self.player1_position == self.data.goal1
&& self.player2_position == self.data.goal2
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Color(u8, u8, u8);
impl Into<MQColor> for Color {
fn into(self) -> MQColor {
MQColor::from_rgba(self.0, self.1, self.2, 255)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PlayerData {
pub position: (i32, i32),
pub color: Color,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlockData {
pub movable: bool,
pub orientation: u32,
pub color: Color,
pub segments: Vec<[i32; 4]>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LevelData {
pub dimensions: [u32; 2],
pub player1: PlayerData,
pub player2: PlayerData,
pub goal1: (i32, i32),
pub goal2: (i32, i32),
pub blocks: Vec<BlockData>,
}
impl LevelData {
pub fn load_from_string(string: &str) -> Result<Self> {
json5::from_str(string).map_err(|err| err.into())
}
}
#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Copy, Clone)]
pub enum Board {
Left = 0,
Right = 1,
}
impl From<i32> for Board {
fn from(n: i32) -> Self {
match n {
0 => Board::Left,
1 => Board::Right,
_ => panic!("expecting 0 or 1, got {}", n),
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Orientation {
None = 0,
Horizontal = 1,
Vertical = 2,
Both = 3,
}
impl From<u32> for Orientation {
fn from(n: u32) -> Self {
match n {
0 => Orientation::Both,
1 => Orientation::Horizontal,
2 => Orientation::Vertical,
_ => panic!("expecting 0..2, got {}", n),
}
}
}
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum PushDir {
Up,
Down,
Left,
Right,
}
impl PushDir {
pub fn as_pair(self) -> (i32, i32) {
match self {
PushDir::Up => (0, -1),
PushDir::Down => (0, 1),
PushDir::Left => (-1, 0),
PushDir::Right => (1, 0),
}
}
}
impl Add<PushDir> for (i32, i32, Board) {
type Output = (i32, i32, Board);
fn add(self, rhs: PushDir) -> Self::Output {
let offset = rhs.as_pair();
(self.0 + offset.0, self.1 + offset.1, self.2)
}
}
// /\
// /21\
// \34/
// \/
#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
pub enum Shape {
Full = 0,
TopRight = 1,
TopLeft = 2,
BottomLeft = 3,
BottomRight = 4,
}
impl From<i32> for Shape {
fn from(n: i32) -> Self {
match n {
0 => Shape::Full,
1 => Shape::TopRight,
2 => Shape::TopLeft,
3 => Shape::BottomLeft,
4 => Shape::BottomRight,
_ => panic!("expecting 0..4, got {}", n),
}
}
}
impl Shape {
pub fn get_opposite(self) -> Option<Shape> {
use Shape::*;
match self {
TopRight => Some(BottomLeft),
BottomLeft => Some(TopRight),
TopLeft => Some(BottomRight),
BottomRight => Some(TopLeft),
Full => None,
}
}
pub fn is_opposite(self, other: Shape) -> bool {
self
.get_opposite()
.map(|shape| shape == other)
.unwrap_or_else(|| false)
}
}

View file

@ -0,0 +1,245 @@
use std::collections::HashSet;
use crate::game_state::{level::Entity, Board, Orientation, PushDir, Shape};
use super::{
level::{ChangeSet, FailSet},
LevelState, SegmentState,
};
impl LevelState {
pub fn player_can_move(
&self,
board: Board,
direction: PushDir,
change_set: ChangeSet,
) -> Result<ChangeSet, FailSet> {
let player_position = match board {
Board::Left => &self.player1_position,
Board::Right => &self.player2_position,
};
let player_segment = SegmentState {
position: *player_position,
shape: Shape::Full,
board,
};
self.segment_can_move(None, player_segment, direction, change_set)
}
fn block_can_move(
&self,
index: usize,
direction: PushDir,
mut change_set: ChangeSet,
) -> Result<ChangeSet, FailSet> {
println!("block_can_move({:?}, {:?})", index, direction);
let block = match self.blocks.get(index) {
Some(block) => block,
None => return Err(HashSet::new()),
};
// is the block even movable?
if !block.movable {
return Err(set!(index));
}
// does the direction match the orientation?
match (block.orientation, direction) {
(Orientation::Horizontal, PushDir::Left)
| (Orientation::Horizontal, PushDir::Right)
| (Orientation::Vertical, PushDir::Up)
| (Orientation::Vertical, PushDir::Down)
| (Orientation::Both, _) => (),
_ => return Err(set!(index)),
}
// TODO: change this to use &mut instead of returning a new one each time
change_set.insert(Entity::Block(index), direction);
for segment in block.segments.iter() {
match self.segment_can_move(
Some(index),
segment.clone(),
direction,
change_set.clone(),
) {
Ok(new_change_set) => change_set = new_change_set,
Err(fail_set) => return Err(fail_set),
}
}
Ok(change_set)
}
fn segment_can_move(
&self,
block_index: Option<usize>,
segment: SegmentState,
direction: PushDir,
change_set: ChangeSet,
) -> Result<ChangeSet, FailSet> {
println!(
"segment_can_move({:?}, {:?}, {:?})",
block_index, segment, direction
);
let segment_loc = (segment.position.0, segment.position.1, segment.board);
let target = segment_loc + direction;
println!(" - target: {:?}", target);
// is the target actually in the map?
if target.0 < 0
|| target.0 >= self.data.dimensions[0] as i32
|| target.1 < 0
|| target.1 >= self.data.dimensions[1] as i32
{
return Err(entity_fail!(block_index));
}
// retrieve other blocks that might be occupying this current space and the target space
let mut current_occupant = None;
let mut target_occupant = None;
for (i, block) in self.blocks.iter().enumerate() {
// skip other segments of the same block
if let Some(n) = block_index {
if n == i {
continue;
}
}
// offset from the change set
let offset = match change_set.get(&Entity::Block(i)) {
Some(direction) => direction.as_pair(),
None => (0, 0),
};
for segment in block.segments.iter() {
// don't get segments on different boards
if segment.board != segment_loc.2 {
continue;
}
let mut segment_pos = segment.position;
if segment_pos == (segment_loc.0, segment_loc.1) {
current_occupant = Some((i, segment.shape, block.orientation));
}
segment_pos.0 += offset.0;
segment_pos.1 += offset.1;
if segment_pos == (target.0, target.1) {
target_occupant =
Some((Entity::Block(i), segment.shape, block.orientation));
}
}
}
// check if the target occupant is actually a player
if let None = target_occupant {
if segment.board == Board::Left
&& self.player1_position == (target.0, target.1)
{
target_occupant =
Some((Entity::Player(Board::Left), Shape::Full, Orientation::None));
} else if segment.board == Board::Right
&& self.player2_position == (target.0, target.1)
{
target_occupant =
Some((Entity::Player(Board::Right), Shape::Full, Orientation::None));
}
}
println!(
" - occupants: current={:?} | target={:?}",
current_occupant, target_occupant
);
// handle special pushes
if let Some((other_block, other_shape, other_orientation)) =
current_occupant
{
// are both shapes triangles?
let both_triangles = match (segment.shape, other_shape) {
(Shape::Full, Shape::Full) => false,
(Shape::Full, _) => unreachable!("invalid to have triangle + full"),
(_, Shape::Full) => unreachable!("invalid to have triangle + full"),
_ => true,
};
if both_triangles {
// what directions could we be pushing the other block into?
let possible_directions = match segment.shape {
Shape::TopRight => [PushDir::Up, PushDir::Right],
Shape::TopLeft => [PushDir::Left, PushDir::Up],
Shape::BottomLeft => [PushDir::Down, PushDir::Left],
Shape::BottomRight => [PushDir::Right, PushDir::Down],
Shape::Full => unreachable!("already eliminated this possibility"),
};
println!(" - possible directions: {:?}", possible_directions);
// does the direction we're pushing appear in this list?
if possible_directions.contains(&direction) {
// the other shape goes in the other direction
let other_direction = match other_orientation {
Orientation::None => {
unreachable!("already eliminated this possibility")
}
Orientation::Vertical => [PushDir::Up, PushDir::Down],
Orientation::Horizontal => [PushDir::Left, PushDir::Right],
Orientation::Both => unimplemented!(),
};
let possible_directions =
possible_directions.iter().collect::<HashSet<_>>();
let other_direction = other_direction.iter().collect();
let mut intersected_direction =
possible_directions.intersection(&other_direction);
let new_direction = **intersected_direction.next().unwrap();
// let other_direction = {
// let mut set = possible_directions.iter().collect::<HashSet<_>>();
// set.remove(&direction);
// *set.into_iter().next().unwrap()
// };
let mut result =
self.block_can_move(other_block, new_direction, change_set);
if let Ok(ref mut change_set) = result {
change_set.insert(Entity::Block(other_block), new_direction);
}
return result;
}
}
}
// handle normal pushes
if let Some((entity, shape, _orientation)) = target_occupant {
match entity {
Entity::Player(_) => {
// TODO: assert that the board is the same
Err(fail_set!(change_set))
}
Entity::Block(index) => {
if
// if it's part of the same block it's ok to push
block_index.is_some() && block_index.unwrap() == index ||
// if the shapes are opposite, we can actually both fit into the same spot
segment.shape.is_opposite(shape)
{
Ok(change_set)
}
// if the block is already in the change set, it can't move
else if change_set.contains_key(&Entity::Block(index)) {
Err(fail_set!(change_set))
}
// if the next block can move then so can this one
else {
self.block_can_move(index, direction, change_set)
}
}
}
} else {
// coast is clear, push away!
Ok(change_set)
}
}
}

183
src/game_state/render.rs Normal file
View file

@ -0,0 +1,183 @@
use macroquad::color::Color as MQColor;
use macroquad::math::{vec2, Vec2};
use macroquad::{
shapes::draw_rectangle,
window::{screen_height, screen_width},
};
use crate::animations::AnimationState;
use super::{Board, Color, LevelState, Orientation, Shape};
impl LevelState {
pub fn render(&self, animations: &AnimationState) {
let width = screen_width();
let height = screen_height();
// board positioning calculations
let playfield_ratio = (2 * self.data.dimensions[0] + 6) as f32
/ (self.data.dimensions[1] + 4) as f32;
let screen_ratio = width / height;
let cols = self.data.dimensions[0] as i32;
let rows = self.data.dimensions[1] as i32;
let (scale, xoff, yoff) = if playfield_ratio > screen_ratio {
let scale = width as f32 / (2 * cols + 6) as f32;
let yoff = height as f32 / 2.0 - (rows + 4) as f32 * scale / 2.0;
(scale, 0.0, yoff)
} else {
let scale = height as f32 / (rows + 4) as f32;
let xoff = width as f32 / 2.0 - (2 * cols + 6) as f32 * scale / 2.0;
(scale, xoff, 0.0)
};
let left_offset = vec2(xoff, yoff);
self.render_boards(scale, left_offset, animations);
}
fn render_boards(
&self,
scale: f32,
offset: Vec2,
animations: &AnimationState,
) {
let left_off = (offset.0 + 2 * scale, offset.1 + 2 * scale);
let right_off = (
offset.0 + (4 + self.data.dimensions[0] as i32) * scale,
offset.1 + 2 * scale,
);
// render the grid
// TODO: do this in one single pass instead of once for each cell
for x in 0..self.data.dimensions[0] as i32 {
for y in 0..self.data.dimensions[1] as i32 {
self
.render_cell((left_off.0 + x * scale, left_off.1 + y * scale), scale);
self.render_cell(
(right_off.0 + x * scale, right_off.1 + y * scale),
scale,
);
}
}
// render blocks
for (i, block) in self.blocks.iter().enumerate() {
for segment in block.segments.iter() {
let offset = match &segment.board {
Board::Left => left_off,
Board::Right => right_off,
};
let mut location = (
offset.0 + segment.position.0 * scale,
offset.1 + segment.position.1 * scale,
);
let animation_offset = animations.get_block_offset(i);
location.0 += (animation_offset.0 * scale as f32) as i32;
location.1 += (animation_offset.1 * scale as f32) as i32;
self.render_segment(
location,
scale,
block.color,
block.orientation,
segment.shape,
);
}
}
// render goals
self.render_goal(self.data.goal1, scale, left_off);
self.render_goal(self.data.goal2, scale, right_off);
// render player
self.render_player(
Board::Left,
self.player1_position,
self.data.player1.color,
scale,
animations,
left_off,
);
self.render_player(
Board::Right,
self.player2_position,
self.data.player1.color,
scale,
animations,
right_off,
);
}
fn render_player(
&self,
board: Board,
player_position: (i32, i32),
player_color: Color,
scale: i32,
animations: &AnimationState,
offset: (i32, i32),
) {
let mut location = (
offset.0 + player_position.0 * scale + 4,
offset.1 + player_position.1 * scale + 4,
);
let animation_offset = animations.get_player_offset(board);
location.0 += (animation_offset.0 * scale as f32) as i32;
location.1 += (animation_offset.1 * scale as f32) as i32;
self.render_segment(
location,
scale - 8,
player_color,
Orientation::Both,
Shape::Full,
);
}
fn render_goal(&self, location: (i32, i32), scale: f32, offset: (i32, i32)) {
let position = (
offset.0 + location.0 * scale + 4,
offset.1 + location.1 * scale + 4,
);
self.render_segment(
position,
scale - 8,
Color(102, 204, 102),
Orientation::Both,
Shape::Full,
);
}
fn render_cell(&self, location: (i32, i32), scale: f32) {
let new_x = location.0 * scale;
let new_y = location.1 * scale;
let color = MQColor::from_rgba(153, 153, 153, 255);
draw_rectangle(
new_x as f32,
new_y as f32,
scale as f32,
scale as f32,
color.into(),
)
}
fn render_segment(
&self,
location: (i32, i32),
scale: i32,
color: Color,
orientation: Orientation,
shape: Shape,
) {
// draw_circle(
// location.0 as f32,
// location.1 as f32,
// scale as f32 * 0.8,
// color.into(),
// );
}
}

30
src/macros.rs Normal file
View file

@ -0,0 +1,30 @@
macro_rules! set {
($($item:expr)*) => {
{
let mut set = std::collections::HashSet::new();
$(set.insert($item);)*
set
}
}
}
macro_rules! fail_set {
($change_set:expr) => {
$change_set
.iter()
.filter_map(|(entity, _)| match entity {
Entity::Block(index) => Some(*index),
Entity::Player(_) => None,
})
.collect()
};
}
macro_rules! entity_fail {
($item:expr) => {
match $item {
Some(index) => set!(index),
None => std::collections::HashSet::new(),
}
};
}

View file

@ -1,165 +1,46 @@
use std::borrow::Cow;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
#[macro_use]
extern crate serde;
#[macro_use]
pub mod macros;
pub mod animations;
pub mod draw;
pub mod game_state;
pub mod screens;
use anyhow::Result;
use macroquad::{
prelude::*,
ui::{hash, root_ui, widgets::Window},
};
use screens::{Screen, ScreenAction};
async fn run(event_loop: EventLoop<()>, window: Window) {
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::Backends::all());
let surface = unsafe { instance.create_surface(&window) };
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
// Request an adapter which can render to our surface
compatible_surface: Some(&surface),
})
.await
.expect("Failed to find an appropriate adapter");
use crate::screens::{MenuScreen, ScreenStack};
// Create the logical device and command queue
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::empty(),
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the swapchain.
limits: wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits()),
},
None,
)
.await
.expect("Failed to create device");
#[macroquad::main("BasicShapes")]
async fn main() -> Result<()> {
let mut screen_stack = ScreenStack::with(MenuScreen::new());
// Load the shaders from disk
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
loop {
clear_background(WHITE);
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
push_constant_ranges: &[],
});
Window::new(hash!(), vec2(20., 20.), vec2(120., 120.))
.titlebar(true)
.label("level control")
.ui(&mut root_ui(), |ui| {
ui.button(vec2(0., 0.), "helloge");
let swapchain_format = surface.get_supported_formats(&adapter)[0];
let top = screen_stack.top();
let top = top.as_ref();
ui.label(vec2(0.0, 10.0), &format!("screen: {}", top.status()));
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(swapchain_format.into())],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
screen_stack.render();
screen_stack.update();
let mut config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: swapchain_format,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: surface.get_supported_alpha_modes(&adapter)[0],
};
next_frame().await
}
surface.configure(&device, &config);
event_loop.run(move |event, _, control_flow| {
// Have the closure take ownership of the resources.
// `event_loop.run` never returns, therefore we must do this to ensure
// the resources are properly cleaned up.
let _ = (&instance, &adapter, &shader, &pipeline_layout);
*control_flow = ControlFlow::Wait;
match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
// Reconfigure the surface with the new size
config.width = size.width;
config.height = size.height;
surface.configure(&device, &config);
// On macos the window needs to be redrawn manually after resizing
window.request_redraw();
}
Event::RedrawRequested(_) => {
let frame = surface
.get_current_texture()
.expect("Failed to acquire next swap chain texture");
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: true,
},
})],
depth_stencil_attachment: None,
});
rpass.set_pipeline(&render_pipeline);
rpass.draw(0..3, 0..1);
}
queue.submit(Some(encoder.finish()));
frame.present();
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => {}
}
});
}
fn main() {
let event_loop = EventLoop::new();
let window = winit::window::Window::new(&event_loop).unwrap();
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
// Temporarily avoid srgb formats for the swapchain on the web
pollster::block_on(run(event_loop, window));
}
#[cfg(target_arch = "wasm32")]
{
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
use winit::platform::web::WindowExtWebSys;
// On wasm, append the canvas to the document body
web_sys::window()
.and_then(|win| win.document())
.and_then(|doc| doc.body())
.and_then(|body| {
body.append_child(&web_sys::Element::from(window.canvas()))
.ok()
})
.expect("couldn't append canvas to document body");
wasm_bindgen_futures::spawn_local(run(event_loop, window));
}
Ok(())
}

27
src/screens/menu.rs Normal file
View file

@ -0,0 +1,27 @@
use macroquad::{input::is_key_pressed, miniquad::KeyCode};
// use crate::keymap::Keymap;
use crate::screens::{PlayScreen, Screen, ScreenAction};
pub struct MenuScreen;
impl Screen for MenuScreen {
fn status(&self) -> String {
format!("menu screen")
}
fn update(&mut self) -> ScreenAction {
if is_key_pressed(KeyCode::Space) {
let play_screen = PlayScreen::new();
ScreenAction::Push(Box::new(play_screen))
} else {
ScreenAction::None
}
}
}
impl MenuScreen {
pub fn new() -> MenuScreen {
MenuScreen
}
}

59
src/screens/mod.rs Normal file
View file

@ -0,0 +1,59 @@
mod menu;
mod play;
pub use self::menu::MenuScreen;
pub use self::play::PlayScreen;
pub trait Screen {
fn status(&self) -> String;
fn update(&mut self) -> ScreenAction {
ScreenAction::None
}
fn render(&self) {}
}
pub enum ScreenAction {
None,
Push(Box<dyn Screen>),
}
pub struct ScreenStack(Vec<Box<dyn Screen>>);
impl ScreenStack {
pub fn with<S: Screen + 'static>(screen: S) -> Self {
let mut stack = Vec::<Box<dyn Screen>>::new();
stack.push(Box::new(screen));
ScreenStack(stack)
}
pub fn top(&self) -> impl AsRef<dyn Screen + 'static> + '_ {
self.0.last().unwrap()
}
pub fn top_mut(&mut self) -> impl AsMut<dyn Screen + 'static> + '_ {
self.0.last_mut().unwrap()
}
pub fn update(&mut self) {
let result = {
let mut screen = self.top_mut();
let screen = screen.as_mut();
screen.update()
};
match result {
ScreenAction::None => (),
ScreenAction::Push(new_screen) => {
println!("pushed new screen");
self.0.push(new_screen);
}
}
}
pub fn render(&self) {
let screen = self.top();
let screen = screen.as_ref();
screen.render()
}
}

136
src/screens/play.rs Normal file
View file

@ -0,0 +1,136 @@
use std::time::Duration;
use macroquad::{
input::is_key_pressed, miniquad::KeyCode, time::get_frame_time,
};
use crate::{
animations::AnimationState,
game_state::{Board, LevelData, LevelState, PushDir},
screens::{Screen, ScreenAction},
};
const LEVEL_TUTORIAL: &str = include_str!("../../levels/tutorial.json");
const LEVEL_TUTORIAL2: &str = include_str!("../../levels/tutorial2.json");
const LEVEL_1: &str = include_str!("../../levels/level1.json");
pub struct PlayScreen {
animations: AnimationState,
levels: Vec<&'static str>,
current_level: LevelState,
current_level_idx: usize,
}
impl Screen for PlayScreen {
fn status(&self) -> String {
format!("play screen")
}
fn update(&mut self) -> ScreenAction {
macro_rules! btn_handler {
($key:expr, $board:expr, $direction:expr) => {
if is_key_pressed($key) {
println!("pushed: {:?}", $key);
let level = self.get_current_level_mut();
let result = level.try_move($board, $direction);
self.animations.begin_move_transition(result);
}
};
}
if self.animations.is_animating {
let delta = Duration::from_secs_f32(get_frame_time());
self.animations.make_progress(delta);
// we just finished!
if !self.animations.is_animating {
// apply the changes to the entities
// this indirection is used to dodge a concurrent borrow
let change_set =
if let Some(Ok(change_set)) = &self.animations.last_move_result {
Some(change_set.clone())
} else {
None
};
if let Some(change_set) = change_set {
let level = self.get_current_level_mut();
level.apply_change_set(change_set.clone());
self.check_win_condition();
}
}
} else {
btn_handler!(KeyCode::W, Board::Left, PushDir::Up);
btn_handler!(KeyCode::A, Board::Left, PushDir::Left);
btn_handler!(KeyCode::S, Board::Left, PushDir::Down);
btn_handler!(KeyCode::D, Board::Left, PushDir::Right);
btn_handler!(KeyCode::I, Board::Right, PushDir::Up);
btn_handler!(KeyCode::J, Board::Right, PushDir::Left);
btn_handler!(KeyCode::K, Board::Right, PushDir::Down);
btn_handler!(KeyCode::L, Board::Right, PushDir::Right);
if is_key_pressed(KeyCode::R) {
// restart the level
self.restart_level();
}
}
ScreenAction::None
}
fn render(&self) {
let level = self.get_current_level();
level.render(&self.animations);
}
}
impl PlayScreen {
pub fn get_current_level(&self) -> &LevelState {
&self.current_level
}
pub fn get_current_level_mut(&mut self) -> &mut LevelState {
&mut self.current_level
}
pub fn new() -> PlayScreen {
let levels = vec![LEVEL_TUTORIAL, LEVEL_TUTORIAL2, LEVEL_1];
PlayScreen {
levels,
current_level: LevelState::new(
LevelData::load_from_string(&LEVEL_TUTORIAL).unwrap(),
),
current_level_idx: 0,
animations: AnimationState::new(),
}
}
fn restart_level(&mut self) {
self.switch_to_level(self.current_level_idx);
}
fn switch_to_level(&mut self, idx: usize) {
self.current_level =
LevelState::new(LevelData::load_from_string(&self.levels[idx]).unwrap());
self.current_level_idx = idx;
}
fn go_to_next_level(&mut self) {
// TODO: make an actual win screen
let next_level = if self.current_level_idx + 1 >= self.levels.len() {
0
} else {
self.current_level_idx + 1
};
self.switch_to_level(next_level);
}
fn check_win_condition(&mut self) {
let level = self.get_current_level();
if level.check_win_condition() {
// go on to the next level
self.go_to_next_level();
}
}
}

View file

@ -1,11 +0,0 @@
@vertex
fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4<f32> {
let x = f32(i32(in_vertex_index) - 1);
let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment
fn fs_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}