Compare commits

...

No commits in common. "rewrite" and "ggez" have entirely different histories.

24 changed files with 2466 additions and 1794 deletions

View file

@ -1,2 +0,0 @@
[alias]
run-wasm = "run --release --package run-wasm --"

1
.envrc
View file

@ -1 +0,0 @@
# use flake

8
.gitignore vendored
View file

@ -1,13 +1,5 @@
/target /target
**/*.rs.bk **/*.rs.bk
.direnv
# Added by cargo
#
# already existing elements were commented out
#/target
# Added by cargo # Added by cargo

2612
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,8 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = "1.0.79" ggez = "0.6.1"
json5 = "0.4.1"
macroquad = "0.4.4"
serde = { version = "1.0.195", features = ["derive"] }
serde_json = "1.0.111"

View file

@ -1,12 +0,0 @@
{ rustc, cargo, makeRustPlatform, cmake, pkg-config, fontconfig }:
let rustPlatform = makeRustPlatform { inherit cargo rustc; };
in rustPlatform.buildRustPackage {
name = "wedge";
src = ./.;
cargoLock.lockFile = ./Cargo.lock;
nativeBuildInputs = [ cmake pkg-config ];
buildInputs = [ fontconfig ];
}

View file

@ -1,97 +0,0 @@
{
"nodes": {
"fenix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1706163833,
"narHash": "sha256-Vw+jTVtKceT+ScaIn7tHy8JjRZZpmg2fAdoInLAsW/M=",
"owner": "nix-community",
"repo": "fenix",
"rev": "043f63f55e9c9b808852ea82edee1f2a1af37e91",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "fenix",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1705309234,
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
"id": "flake-utils",
"type": "indirect"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1706006310,
"narHash": "sha256-nDPz0fj0IFcDhSTlXBU2aixcnGs2Jm4Zcuoj0QtmiXQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b43bb235efeab5324c5e486882ef46749188eee2",
"type": "github"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"root": {
"inputs": {
"fenix": "fenix",
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1706106882,
"narHash": "sha256-31DivWu0cC50gR2CgbGtLCf77nuiw4kdiI7B8ioqzLw=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "0d52934d19d7addcafcfda92a1d547b51556beec",
"type": "github"
},
"original": {
"owner": "rust-lang",
"ref": "nightly",
"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",
"version": 7
}

View file

@ -1,64 +0,0 @@
{
inputs = {
fenix = {
url = "github:nix-community/fenix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, flake-utils, fenix }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = import nixpkgs {
inherit system;
overlays = [ fenix.overlays.default ];
};
rustc = pkgs.fenix.stable.rustc;
cargo = pkgs.fenix.stable.cargo;
neededLibs = with pkgs;
(with xorg; [ ])
++ [ ];
flakePkgs = { wedge = pkgs.callPackage ./. { inherit rustc cargo; }; };
in
rec {
packages = flake-utils.lib.flattenTree flakePkgs;
defaultPackage = packages.wedge;
devShell = pkgs.mkShell {
inputsFrom = with packages; [ wedge ];
shellHook = ''
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${
pkgs.lib.makeLibraryPath neededLibs
}"
'';
packages = (with pkgs; [
# cargo-watch
# cargo-deny
# cargo-edit
# sqlx-cli
# sqlite
(with pkgs.fenix;
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"
];
};
});
}

View file

@ -1,124 +0,0 @@
{
"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],
],
},
],
}

View file

@ -1,67 +0,0 @@
{
"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],
],
},
]
}

View file

@ -1,54 +0,0 @@
{
"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,4 +0,0 @@
max_width = 80
tab_spaces = 2
wrap_comments = true
fn_single_line = true

View file

@ -1,116 +0,0 @@
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))
}
}

View file

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

View file

@ -1,35 +0,0 @@
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,
}
}
}

View file

@ -1,48 +0,0 @@
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)
}
}

View file

@ -1,197 +0,0 @@
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

@ -1,245 +0,0 @@
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)
}
}
}

View file

@ -1,183 +0,0 @@
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(),
// );
}
}

View file

@ -1,30 +0,0 @@
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,46 +1,55 @@
#[macro_use] mod screens;
extern crate serde;
#[macro_use] use std::time::Instant;
pub mod macros;
pub mod animations; use ggez::event::{self, EventHandler};
pub mod draw; use ggez::graphics::{self, Color};
pub mod game_state; use ggez::{Context, ContextBuilder, GameResult};
pub mod screens;
use anyhow::Result; use crate::screens::{Screens, Screen};
use macroquad::{ use crate::screens::menu::MenuScreen;
prelude::*,
ui::{hash, root_ui, widgets::Window},
};
use screens::{Screen, ScreenAction};
use crate::screens::{MenuScreen, ScreenStack}; fn main() {
// Make a Context.
let (mut ctx, event_loop) = ContextBuilder::new("my_game", "Cool Game Author")
.build()
.expect("aieee, could not create ggez context!");
#[macroquad::main("BasicShapes")] // Create an instance of your event handler.
async fn main() -> Result<()> { // Usually, you should provide it with the Context object to
let mut screen_stack = ScreenStack::with(MenuScreen::new()); // use when setting your game up.
let my_game = MyGame::new(&mut ctx);
loop { // Run!
clear_background(WHITE); event::run(ctx, event_loop, my_game);
}
Window::new(hash!(), vec2(20., 20.), vec2(120., 120.))
.titlebar(true) struct MyGame {
.label("level control") screens: Screens,
.ui(&mut root_ui(), |ui| { last_update: Instant,
ui.button(vec2(0., 0.), "helloge"); }
let top = screen_stack.top(); impl MyGame {
let top = top.as_ref(); pub fn new(_ctx: &mut Context) -> MyGame {
ui.label(vec2(0.0, 10.0), &format!("screen: {}", top.status())); // Load/create resources such as images here.
}); MyGame {
last_update: Instant::now(),
screen_stack.render(); screens: Screens::init(Screen::Menu(MenuScreen::default())),
screen_stack.update(); }
}
next_frame().await }
}
impl EventHandler<ggez::GameError> for MyGame {
Ok(()) fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
let now = Instant::now();
let elapsed = now - self.last_update;
self.screens.update(elapsed);
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
graphics::clear(ctx, Color::WHITE);
self.screens.render(ctx);
graphics::present(ctx)
}
} }

View file

@ -1,27 +1,18 @@
use macroquad::{input::is_key_pressed, miniquad::KeyCode}; use std::time::Duration;
// use crate::keymap::Keymap; use ggez::Context;
use crate::screens::{PlayScreen, Screen, ScreenAction};
pub struct MenuScreen; use super::ScreenAction;
impl Screen for MenuScreen { #[derive(Default)]
fn status(&self) -> String { pub struct MenuScreen {
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 { impl MenuScreen {
pub fn new() -> MenuScreen { pub fn update(&mut self, delta: Duration) -> ScreenAction {
MenuScreen ScreenAction::None
} }
pub fn render(&self, ctx: &mut Context) {
}
} }

View file

@ -1,59 +1,65 @@
mod menu; pub mod menu;
mod play;
pub use self::menu::MenuScreen; use std::time::Duration;
pub use self::play::PlayScreen;
pub trait Screen { use ggez::Context;
fn status(&self) -> String;
fn update(&mut self) -> ScreenAction { use self::menu::MenuScreen;
ScreenAction::None
}
fn render(&self) {} pub struct Screens {
stack: Vec<Screen>,
} }
pub enum ScreenAction { pub enum ScreenAction {
None, None,
Push(Box<dyn Screen>), Push(Screen),
} }
pub struct ScreenStack(Vec<Box<dyn Screen>>); impl Screens {
pub fn init(base: Screen) -> Self {
impl ScreenStack { Screens {
pub fn with<S: Screen + 'static>(screen: S) -> Self { stack: vec![ base ],
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) { fn top(&self) -> &Screen {
let screen = self.top(); self.stack.last().unwrap()
let screen = screen.as_ref(); }
screen.render()
} fn top_mut(&mut self) -> &mut Screen {
self.stack.last_mut().unwrap()
}
pub fn update(&mut self, delta: Duration) {
let top = self.top_mut();
match top.update(delta) {
ScreenAction::None => (),
ScreenAction::Push(new) => {
self.stack.push(new);
}
}
}
pub fn render(&self, ctx: &mut Context) {
let top = self.top();
top.render(ctx);
}
}
pub enum Screen {
Menu(MenuScreen),
}
impl Screen {
fn update(&mut self, delta: Duration) -> ScreenAction {
match self {
Screen::Menu(screen) => screen.update(delta),
}
}
fn render(&self, ctx: &mut Context) {
match self {
Screen::Menu(screen) => screen.render(ctx),
}
}
} }

View file

@ -1,136 +0,0 @@
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();
}
}
}