Merge branch 'dev' into 'main'

Merge Sprint 2

See merge request softwaregrundprojekt/2025-2026/einzelprojekt/tutorium-moritz/bernroider-dominik/bernroider-dominik!16
This commit is contained in:
Moritz Peter Maile
2025-11-28 16:37:06 +00:00
60 changed files with 2082 additions and 365 deletions

68
Cargo.lock generated
View File

@@ -88,7 +88,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"getrandom", "getrandom 0.3.4",
"once_cell", "once_cell",
"version_check", "version_check",
"zerocopy", "zerocopy",
@@ -1092,7 +1092,7 @@ dependencies = [
"critical-section", "critical-section",
"foldhash 0.2.0", "foldhash 0.2.0",
"futures-channel", "futures-channel",
"getrandom", "getrandom 0.3.4",
"hashbrown 0.16.0", "hashbrown 0.16.0",
"js-sys", "js-sys",
"portable-atomic", "portable-atomic",
@@ -2079,6 +2079,27 @@ dependencies = [
"unicode-xid", "unicode-xid",
] ]
[[package]]
name = "directories"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "dispatch" name = "dispatch"
version = "0.2.0" version = "0.2.0"
@@ -2380,6 +2401,17 @@ dependencies = [
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
[[package]]
name = "getrandom"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.3.4" version = "0.3.4"
@@ -2783,7 +2815,7 @@ version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
dependencies = [ dependencies = [
"getrandom", "getrandom 0.3.4",
"libc", "libc",
] ]
@@ -3464,6 +3496,12 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]] [[package]]
name = "orbclient" name = "orbclient"
version = "0.3.48" version = "0.3.48"
@@ -3622,6 +3660,9 @@ dependencies = [
"bevy", "bevy",
"bevy_aseprite_ultra", "bevy_aseprite_ultra",
"bevy_dev_tools", "bevy_dev_tools",
"directories",
"serde",
"serde_json",
] ]
[[package]] [[package]]
@@ -3752,7 +3793,7 @@ version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [ dependencies = [
"getrandom", "getrandom 0.3.4",
] ]
[[package]] [[package]]
@@ -3817,6 +3858,17 @@ dependencies = [
"bitflags 2.9.4", "bitflags 2.9.4",
] ]
[[package]]
name = "redox_users"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
dependencies = [
"getrandom 0.2.16",
"libredox",
"thiserror 2.0.17",
]
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.12.2" version = "1.12.2"
@@ -4573,7 +4625,7 @@ version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
dependencies = [ dependencies = [
"getrandom", "getrandom 0.3.4",
"js-sys", "js-sys",
"serde", "serde",
"wasm-bindgen", "wasm-bindgen",
@@ -4618,6 +4670,12 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]] [[package]]
name = "wasip2" name = "wasip2"
version = "1.0.1+wasi-0.2.4" version = "1.0.1+wasi-0.2.4"

View File

@@ -17,3 +17,6 @@ lto = "thin"
bevy = "0.17.2" bevy = "0.17.2"
bevy_aseprite_ultra = "0.7.0" bevy_aseprite_ultra = "0.7.0"
bevy_dev_tools = "0.17.2" bevy_dev_tools = "0.17.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
directories = "6.0"

7
LICENSE Normal file
View File

@@ -0,0 +1,7 @@
Copyright 2025 Dominik Bernroider
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

108
README.md
View File

@@ -1,93 +1,49 @@
# bernroider-dominik # Pomomon Garden ![Sleeping Pom](pom-sleep.gif)
Pomomon Garden is a Pomodoro game created during ["Sopra" (Softwareprojekt)](https://www.uni-ulm.de/in/sgi/lehre/softwaojekt-sopra-1/) WiSe 25/26 at the University of Ulm.
It uses the [ECS](https://en.wikipedia.org/wiki/Entity_component_system)-based Rust game engine called [Bevy](https://bevy.org/).
---
## Getting started ## About the game
To make it easy for you to get started with GitLab, here's a list of recommended next steps. The game switches between the focus and pause phase. In the focus phase the player is expected to study/work/... while the timer ticks down.
After the timer runs out, the player is prompted to switch to the pause phase.
In this phase he can interact with his farm using Pom, the playable character.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! ---
## Add your files ## Build and debug instructions
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files ### Building
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
``` #### Using [Nix Flakes](https://nixos.wiki/wiki/Flakes):
cd existing_repo
git remote add origin https://gitlab.uni-ulm.de/softwaregrundprojekt/2025-2026/einzelprojekt/tutorium-moritz/bernroider-dominik/bernroider-dominik.git ```sh
git branch -M main git clone https://gitlab.uni-ulm.de/softwaregrundprojekt/2025-2026/einzelprojekt/tutorium-moritz/bernroider-dominik/bernroider-dominik pomomon-garden
git push -uf origin main cd pomomon-garden
nix develop
cargo run
``` ```
## Integrate with your tools #### Other:
- [ ] [Set up project integrations](https://gitlab.uni-ulm.de/softwaregrundprojekt/2025-2026/einzelprojekt/tutorium-moritz/bernroider-dominik/bernroider-dominik/-/settings/integrations) 1. [Install Rust](https://rust-lang.org/tools/install/)
2. [Install Bevy OS depedencies](https://bevy.org/learn/quick-start/getting-started/setup/#installing-os-dependencies)
## Collaborate with your team ```sh
git clone https://gitlab.uni-ulm.de/softwaregrundprojekt/2025-2026/einzelprojekt/tutorium-moritz/bernroider-dominik/bernroider-dominik pomomon-garden
cd pomomon-garden
cargo run
```
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) ### Hidden binds (Only available in the debug build)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy - `Shift + Enter`: Duration of the current phase is set to 3 seconds.
- `Left Mouse Button` on Tile: Rotate tile state.
Use the built-in continuous integration in GitLab. ---
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) ## Licensing
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
*** This project is released under the terms of the [MIT License](LICENSE).
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

5
assets/config.json Normal file
View File

@@ -0,0 +1,5 @@
{
"grid_width": 12,
"grid_height": 4,
"pom_speed": 1.5
}

View File

@@ -107,7 +107,7 @@
] ]
++ bevyDeps; ++ bevyDeps;
inherit CARGO_PROFILE_RELEASE_LTO CARGO_PROFILE_RELEASE_CODEGEN_UNITS CARGO_PROFILE_RELEASE_STRIP RUSTFLAGS; # inherit CARGO_PROFILE_RELEASE_LTO CARGO_PROFILE_RELEASE_CODEGEN_UNITS CARGO_PROFILE_RELEASE_STRIP RUSTFLAGS;
shellHook = '' shellHook = ''
export RUST_SRC_PATH=${fenix.packages.${system}.stable.rust-src}/lib/rustlib/src/rust/library export RUST_SRC_PATH=${fenix.packages.${system}.stable.rust-src}/lib/rustlib/src/rust/library

BIN
pom-sleep.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@@ -1,2 +0,0 @@
pub mod pom;
pub mod tile;

View File

@@ -0,0 +1,28 @@
use crate::prelude::*;
use std::fs::File;
use std::io::BufReader;
#[derive(Resource, Deserialize, Debug)]
pub struct GameConfig {
pub grid_width: u32,
pub grid_height: u32,
pub pom_speed: f32,
}
impl Default for GameConfig {
fn default() -> Self {
Self {
grid_width: 12,
grid_height: 4,
pom_speed: 1.5,
}
}
}
impl GameConfig {
pub fn read_config() -> Option<Self> {
let file = File::open("assets/config.json").ok()?;
let reader = BufReader::new(file);
serde_json::from_reader(reader).ok()
}
}

View File

@@ -0,0 +1 @@
pub mod components;

View File

@@ -1,5 +1,6 @@
use crate::states::*; use crate::prelude::*;
use bevy::prelude::*;
pub mod states;
pub struct CorePlugin; pub struct CorePlugin;

View File

@@ -0,0 +1,8 @@
use crate::prelude::*;
#[derive(States, Clone, PartialEq, Eq, Debug, Hash, Default)]
pub enum AppState {
#[default]
StartScreen,
GameScreen,
}

View File

@@ -0,0 +1,18 @@
use crate::prelude::*;
pub struct GameScreenPlugin;
impl Plugin for GameScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::GameScreen), setup);
app.add_systems(OnExit(AppState::GameScreen), cleanup);
}
}
fn setup(mut clear_color: ResMut<ClearColor>) {
*clear_color = ClearColor(Color::srgb(0.294, 0.412, 0.184));
}
fn cleanup(mut clear_color: ResMut<ClearColor>) {
*clear_color = ClearColor(Color::srgb(0.2, 0.2, 0.2));
}

View File

@@ -1,6 +1,5 @@
use bevy::prelude::*; use super::errors::GridError;
use crate::prelude::*;
use crate::errors::GridError;
#[derive(Component)] #[derive(Component)]
pub struct Tile { pub struct Tile {
@@ -8,7 +7,7 @@ pub struct Tile {
pub y: u32, pub y: u32,
} }
#[derive(Component, Default)] #[derive(Component, Default, Serialize, Deserialize, Clone, Copy, Debug)]
pub enum TileState { pub enum TileState {
#[default] #[default]
Unclaimed, Unclaimed,

View File

@@ -0,0 +1 @@
pub const TILE_SIZE: f32 = 32.0;

View File

@@ -1,16 +1,9 @@
use crate::{ use crate::prelude::*;
components::tile::{Grid, Tile, TileState},
states::AppState,
};
use bevy::prelude::*;
use bevy_aseprite_ultra::prelude::AseSlice;
pub const TILE_SIZE: f32 = 32.0; pub mod components;
pub const GRID_WIDTH: u32 = 10; pub mod consts;
pub const GRID_HEIGHT: u32 = 10; pub mod errors;
pub mod utils;
pub const GRID_START_X: f32 = -(GRID_WIDTH as f32 * TILE_SIZE) / 2.0 + TILE_SIZE / 2.0;
pub const GRID_START_Y: f32 = -(GRID_HEIGHT as f32 * TILE_SIZE) / 2.0 + TILE_SIZE / 2.0;
pub struct GridPlugin; pub struct GridPlugin;
@@ -26,13 +19,15 @@ impl Plugin for GridPlugin {
} }
} }
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { fn setup(mut commands: Commands, asset_server: Res<AssetServer>, config: Res<GameConfig>) {
let mut tiles = Vec::with_capacity(GRID_WIDTH as usize); let grid_width = config.grid_width;
let grid_height = config.grid_height;
let mut tiles = Vec::with_capacity(grid_width as usize);
for x in 0..GRID_WIDTH { for x in 0..grid_width {
let mut column = Vec::with_capacity(GRID_HEIGHT as usize); let mut column = Vec::with_capacity(grid_height as usize);
for y in 0..GRID_HEIGHT { for y in 0..grid_height {
let tile_entity = commands let tile_entity = commands
.spawn(( .spawn((
Tile { x, y }, Tile { x, y },
@@ -42,7 +37,13 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
aseprite: asset_server.load("tiles/tile-unclaimed.aseprite"), aseprite: asset_server.load("tiles/tile-unclaimed.aseprite"),
}, },
Sprite::default(), Sprite::default(),
Transform::from_translation(grid_to_world_coords(x, y, None)), Transform::from_translation(grid_to_world_coords(
x,
y,
None,
grid_width,
grid_height,
)),
)) ))
.id(); .id();
column.push(tile_entity); column.push(tile_entity);
@@ -51,8 +52,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
} }
commands.insert_resource(Grid { commands.insert_resource(Grid {
width: GRID_WIDTH, width: grid_width,
height: GRID_HEIGHT, height: grid_height,
tiles, tiles,
}); });
} }
@@ -83,28 +84,3 @@ fn update_tile_colors(
}; };
} }
} }
pub fn world_to_grid_coords(world_pos: Vec3) -> (u32, u32) {
let x = ((world_pos.x - GRID_START_X + TILE_SIZE / 2.0) / TILE_SIZE).floor();
let y = ((world_pos.y - GRID_START_Y + TILE_SIZE / 2.0) / TILE_SIZE).floor();
let mut x_u32 = x as u32;
let mut y_u32 = y as u32;
if x_u32 >= GRID_WIDTH {
x_u32 = GRID_WIDTH - 1;
}
if y_u32 >= GRID_HEIGHT {
y_u32 = GRID_HEIGHT - 1;
}
(x_u32, y_u32)
}
pub fn grid_to_world_coords(grid_x: u32, grid_y: u32, z: Option<f32>) -> Vec3 {
Vec3::new(
GRID_START_X + grid_x as f32 * TILE_SIZE,
GRID_START_Y + grid_y as f32 * TILE_SIZE,
z.unwrap_or(0.0),
)
}

View File

@@ -0,0 +1,43 @@
use crate::prelude::*;
pub fn grid_start_x(grid_width: u32) -> f32 {
-(grid_width as f32 * TILE_SIZE) / 2.0 + TILE_SIZE / 2.0
}
pub fn grid_start_y(grid_height: u32) -> f32 {
-(grid_height as f32 * TILE_SIZE) / 2.0 + TILE_SIZE / 2.0
}
pub fn world_to_grid_coords(world_pos: Vec3, grid_width: u32, grid_height: u32) -> (u32, u32) {
let start_x = grid_start_x(grid_width);
let start_y = grid_start_y(grid_height);
let x = ((world_pos.x - start_x + TILE_SIZE / 2.0) / TILE_SIZE).floor();
let y = ((world_pos.y - start_y + TILE_SIZE / 2.0) / TILE_SIZE).floor();
let mut x_u32 = x as u32;
let mut y_u32 = y as u32;
if x_u32 >= grid_width {
x_u32 = grid_width - 1;
}
if y_u32 >= grid_height {
y_u32 = grid_height - 1;
}
(x_u32, y_u32)
}
pub fn grid_to_world_coords(
grid_x: u32,
grid_y: u32,
z: Option<f32>,
grid_width: u32,
grid_height: u32,
) -> Vec3 {
Vec3::new(
grid_start_x(grid_width) + grid_x as f32 * TILE_SIZE,
grid_start_y(grid_height) + grid_y as f32 * TILE_SIZE,
z.unwrap_or(0.0),
)
}

View File

@@ -0,0 +1,66 @@
use crate::{features::phase::components::TimerSettings, prelude::*};
#[derive(Component)]
pub enum RootMarker {
Status,
Settings,
}
#[derive(Component)]
pub enum TextType {
Phase,
Timer,
}
#[derive(Component)]
pub enum ButtonType {
SettingsOpen,
SettingsClose,
SettingsExit,
SettingsSave,
SettingsTimerChange {
input: SettingsTimerInput,
amount: i32,
},
}
#[derive(Clone)]
pub enum TimerType {
Focus,
ShortBreak,
LongBreak,
}
impl TimerSettings {
pub fn change(&mut self, timer_type: &TimerType, amount: i32) {
match timer_type {
TimerType::Focus => {
self.focus_duration = (self.focus_duration as i32 + amount) as u32;
if self.focus_duration > 7259 {
// 120:59
self.focus_duration = 7259;
}
}
TimerType::LongBreak => {
self.long_break_duration = (self.long_break_duration as i32 + amount) as u32;
if self.long_break_duration > 7259 {
// 120:59
self.long_break_duration = 7259;
}
}
TimerType::ShortBreak => {
self.short_break_duration = (self.short_break_duration as i32 + amount) as u32;
if self.short_break_duration > 7259 {
// 120:59
self.short_break_duration = 7259;
}
}
}
}
}
#[derive(Component, Clone)]
pub enum SettingsTimerInput {
Minutes(TimerType),
Seconds(TimerType),
}

157
src/features/hud/mod.rs Normal file
View File

@@ -0,0 +1,157 @@
use crate::features::inventory;
use crate::features::phase::components::TimerSettings;
use crate::features::savegame::messages::SavegameDumpMessage;
use crate::prelude::*;
use components::*;
use ui::*;
pub mod components;
pub mod ui;
pub struct HudPlugin;
impl Plugin for HudPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::GameScreen), setup);
app.add_systems(OnExit(AppState::GameScreen), cleanup);
app.add_systems(
Update,
(update_status, buttons, update_timer_settings).run_if(in_state(AppState::GameScreen)),
);
}
}
fn setup(mut commands: Commands) {
commands.spawn((
RootMarker::Status,
Node {
position_type: PositionType::Absolute,
bottom: px(0),
left: px(0),
width: percent(100),
height: px(50),
justify_content: JustifyContent::SpaceAround,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Row,
..default()
},
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.8)),
children![
text_with_component(TextType::Phase, "...", 16.0, Color::WHITE),
text_with_component(TextType::Timer, "...", 16.0, Color::WHITE),
button(
inventory::components::ButtonType::InventoryOpen,
ButtonVariant::Secondary,
Node {
padding: UiRect::all(px(10)),
..default()
},
"Inventar",
16.0
),
button(
ButtonType::SettingsOpen,
ButtonVariant::Secondary,
Node {
padding: UiRect::all(px(10)),
..default()
},
"Einstellungen",
16.0
)
],
));
}
fn update_status(phase_res: Res<CurrentPhase>, mut text_query: Query<(&mut Text, &TextType)>) {
if !phase_res.is_changed() {
return;
}
let current_phase = &phase_res.0;
for (mut text, status_type) in text_query.iter_mut() {
text.0 = match status_type {
TextType::Phase => current_phase.display_name().into(),
TextType::Timer => current_phase.format_duration(),
};
}
}
fn buttons(
mut commands: Commands,
mut interaction_query: Query<(&Interaction, &ButtonType), (Changed<Interaction>, With<Button>)>,
root_query: Query<(Entity, &RootMarker)>,
mut savegame_messages: MessageWriter<SavegameDumpMessage>,
mut next_state: ResMut<NextState<AppState>>,
mut timer_settings: ResMut<TimerSettings>,
) {
for (interaction, button_type) in &mut interaction_query {
match *interaction {
Interaction::Pressed => match button_type {
ButtonType::SettingsOpen => {
open_settings(&mut commands);
}
ButtonType::SettingsClose => {
for (entity, root) in root_query.iter() {
match *root {
RootMarker::Settings => commands.entity(entity).despawn(),
_ => {}
}
}
}
ButtonType::SettingsExit => {
savegame_messages.write(SavegameDumpMessage);
next_state.set(AppState::StartScreen);
}
ButtonType::SettingsSave => {
savegame_messages.write(SavegameDumpMessage);
}
ButtonType::SettingsTimerChange { input, amount } => match input {
SettingsTimerInput::Minutes(timer_type) => {
timer_settings.change(timer_type, 60 * amount)
}
SettingsTimerInput::Seconds(timer_type) => {
timer_settings.change(timer_type, *amount)
}
},
},
_ => {}
}
}
}
fn cleanup(mut commands: Commands, query: Query<Entity, With<RootMarker>>) {
for entity in query.iter() {
commands.entity(entity).despawn();
}
}
fn update_timer_settings(
timer_settings: ResMut<TimerSettings>,
mut query: Query<(&SettingsTimerInput, &mut Text)>,
) {
for (input_type, mut text) in query.iter_mut() {
match input_type {
SettingsTimerInput::Minutes(timer_type) => {
let value = match timer_type {
TimerType::Focus => timer_settings.focus_duration,
TimerType::ShortBreak => timer_settings.short_break_duration,
TimerType::LongBreak => timer_settings.long_break_duration,
} as f32;
text.0 = format!("{:0>2}", (value / 60.0).floor());
}
SettingsTimerInput::Seconds(timer_type) => {
let value = match timer_type {
TimerType::Focus => timer_settings.focus_duration,
TimerType::ShortBreak => timer_settings.short_break_duration,
TimerType::LongBreak => timer_settings.long_break_duration,
};
text.0 = format!("{:0>2}", (value % 60));
}
}
}
}

View File

@@ -0,0 +1,5 @@
pub mod settings;
pub mod timer_settings;
pub use settings::*;
pub use timer_settings::*;

View File

@@ -0,0 +1,131 @@
use super::super::components::*;
use super::timer_settings::timer_settings;
use crate::prelude::*;
pub fn open_settings(commands: &mut Commands) {
commands
.spawn((
RootMarker::Settings,
Node {
position_type: PositionType::Absolute,
width: percent(100),
height: percent(100),
..Node::center()
},
ZIndex(1),
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.8)),
))
.with_children(|parent| {
parent
.spawn((
Node {
width: px(700),
padding: UiRect::all(px(20.0)),
..Node::vstack(px(20))
},
BackgroundColor(Color::srgb(0.2, 0.2, 0.2)),
BorderRadius::all(px(10.0)),
))
.with_children(|parent| {
parent.spawn((
Node {
justify_content: JustifyContent::SpaceBetween,
..Node::hstack(px(20))
},
children![
text("Spiel Einstellungen", 40.0, Color::WHITE),
pill_button(
ButtonType::SettingsClose,
ButtonVariant::Destructive,
Node {
width: px(40),
height: px(40),
..default()
},
"X",
24.0
),
],
));
parent
.spawn(Node::vstack(px(10)))
.with_children(|parent| {
parent.spawn(button(
ButtonType::SettingsExit,
ButtonVariant::Secondary,
Node {
padding: UiRect::all(px(10)),
..default()
},
"Spiel verlassen",
24.0,
));
parent.spawn(button(
ButtonType::SettingsSave,
ButtonVariant::Secondary,
Node {
padding: UiRect::all(px(10)),
..default()
},
"Spiel speichern",
24.0,
));
parent.spawn((
Node {
justify_content: JustifyContent::Center,
..Node::hstack(px(30))
},
children![
(
Node {
width: percent(40),
..Node::vstack(px(10))
},
children![
text("Spiel Einstellungen", 18.0, Color::WHITE),
text(
"Tipp: Benutze [Umstellen] um in 10er Schritten zu inkrementieren oder dekrementieren!",
16.0,
Color::WHITE
),
]
),
(
Node {
align_items: AlignItems::Center,
..Node::vstack(px(10))
},
children![
text("Fokus Phase", 12.0, Color::WHITE),
timer_settings(TimerType::Focus)
]
),
(
Node {
align_items: AlignItems::Center,
..Node::vstack(px(10))
},
children![
text("Kurze Pause", 12.0, Color::WHITE),
timer_settings(TimerType::ShortBreak)
]
),
(
Node {
align_items: AlignItems::Center,
..Node::vstack(px(10))
},
children![
text("Lange Pause", 12.0, Color::WHITE),
timer_settings(TimerType::LongBreak)
]
)
],
));
});
});
});
}

View File

@@ -0,0 +1,51 @@
use super::super::components::*;
use crate::prelude::*;
pub fn timer_settings(timer_type: TimerType) -> impl Bundle {
(
Node {
align_items: AlignItems::Center,
..Node::hstack(px(0))
},
children![
timer_settings_part(SettingsTimerInput::Minutes(timer_type.clone()), 1),
text(":", 24.0, Color::WHITE),
timer_settings_part(SettingsTimerInput::Seconds(timer_type.clone()), 1),
],
)
}
fn timer_settings_part(input: SettingsTimerInput, amount: u32) -> impl Bundle {
(
Node::vstack(px(0)),
children![
button(
ButtonType::SettingsTimerChange {
input: input.clone(),
amount: amount as i32
},
ButtonVariant::Secondary,
Node {
width: percent(100),
..default()
},
"+",
12.0
),
text_with_component(input.clone(), "--", 24.0, Color::WHITE),
button(
ButtonType::SettingsTimerChange {
input: input.clone(),
amount: -(amount as i32)
},
ButtonVariant::Secondary,
Node {
width: percent(100),
..default()
},
"-",
12.0
),
],
)
}

View File

@@ -1,12 +1,11 @@
use crate::features::{
phase::messages::{NextPhaseMessage, PhaseTimerPauseMessage},
pom::messages::InvalidMoveMessage,
};
use crate::prelude::*;
use bevy::input::mouse::MouseButton; use bevy::input::mouse::MouseButton;
use bevy::prelude::*;
use bevy::window::PrimaryWindow; use bevy::window::PrimaryWindow;
use crate::components::tile::{Grid, TileState};
use crate::messages::{InteractStartMessage, InvalidMoveMessage, MoveMessage};
use crate::plugins::grid::world_to_grid_coords;
use crate::states::AppState;
pub struct InputPlugin; pub struct InputPlugin;
impl Plugin for InputPlugin { impl Plugin for InputPlugin {
@@ -20,6 +19,15 @@ impl Plugin for InputPlugin {
Update, Update,
interact_click.run_if(in_state(AppState::GameScreen)), interact_click.run_if(in_state(AppState::GameScreen)),
); );
app.add_message::<PhaseTimerPauseMessage>();
app.add_systems(
Update,
phase_timer_pause.run_if(in_state(AppState::GameScreen)),
);
app.add_message::<NextPhaseMessage>();
app.add_systems(Update, next_phase.run_if(in_state(AppState::GameScreen)));
} }
} }
@@ -28,7 +36,14 @@ fn move_click(
mouse_btn: Res<ButtonInput<MouseButton>>, mouse_btn: Res<ButtonInput<MouseButton>>,
window: Single<&Window, With<PrimaryWindow>>, window: Single<&Window, With<PrimaryWindow>>,
camera: Single<(&Camera, &GlobalTransform), With<Camera2d>>, camera: Single<(&Camera, &GlobalTransform), With<Camera2d>>,
config: Res<GameConfig>,
phase: Res<CurrentPhase>,
) { ) {
match phase.0 {
Phase::Focus { .. } => return,
_ => {}
}
if mouse_btn.just_pressed(MouseButton::Right) { if mouse_btn.just_pressed(MouseButton::Right) {
let (cam, cam_transform) = *camera; let (cam, cam_transform) = *camera;
@@ -38,7 +53,7 @@ fn move_click(
let Ok(world_pos) = cam.viewport_to_world(cam_transform, cursor_pos) else { let Ok(world_pos) = cam.viewport_to_world(cam_transform, cursor_pos) else {
return; return;
}; };
let (x, y) = world_to_grid_coords(world_pos.origin); let (x, y) = world_to_grid_coords(world_pos.origin, config.grid_width, config.grid_height);
println!("Move Click: ({}, {})", x, y); println!("Move Click: ({}, {})", x, y);
move_messages.write(MoveMessage { x, y }); move_messages.write(MoveMessage { x, y });
@@ -50,10 +65,17 @@ fn interact_click(
mouse_btn: Res<ButtonInput<MouseButton>>, mouse_btn: Res<ButtonInput<MouseButton>>,
window: Single<&Window, With<PrimaryWindow>>, window: Single<&Window, With<PrimaryWindow>>,
camera: Single<(&Camera, &GlobalTransform), With<Camera2d>>, camera: Single<(&Camera, &GlobalTransform), With<Camera2d>>,
config: Res<GameConfig>,
phase: Res<CurrentPhase>,
// for debug // for debug
grid: ResMut<Grid>, grid: ResMut<Grid>,
tile_query: Query<&mut TileState>, tile_query: Query<&mut TileState>,
) { ) {
match phase.0 {
Phase::Focus { .. } => return,
_ => {}
}
if mouse_btn.just_pressed(MouseButton::Left) { if mouse_btn.just_pressed(MouseButton::Left) {
let (cam, cam_transform) = *camera; let (cam, cam_transform) = *camera;
@@ -63,7 +85,7 @@ fn interact_click(
let Ok(world_pos) = cam.viewport_to_world(cam_transform, cursor_pos) else { let Ok(world_pos) = cam.viewport_to_world(cam_transform, cursor_pos) else {
return; return;
}; };
let (x, y) = world_to_grid_coords(world_pos.origin); let (x, y) = world_to_grid_coords(world_pos.origin, config.grid_width, config.grid_height);
println!("Interact Click: ({}, {})", x, y); println!("Interact Click: ({}, {})", x, y);
interact_messages.write(InteractStartMessage { x, y }); interact_messages.write(InteractStartMessage { x, y });
@@ -82,3 +104,18 @@ fn interact_click(
} }
} }
} }
fn phase_timer_pause(
mut pause_messages: MessageWriter<PhaseTimerPauseMessage>,
keys: Res<ButtonInput<KeyCode>>,
) {
if keys.just_pressed(KeyCode::Space) {
pause_messages.write(PhaseTimerPauseMessage);
}
}
fn next_phase(mut messages: MessageWriter<NextPhaseMessage>, keys: Res<ButtonInput<KeyCode>>) {
if keys.just_pressed(KeyCode::Enter) {
messages.write(NextPhaseMessage);
}
}

View File

@@ -0,0 +1,51 @@
use crate::prelude::*;
#[derive(Serialize, Deserialize, Clone)]
pub enum ItemType {
Berry,
}
impl ItemType {
pub fn singular(&self) -> String {
match self {
ItemType::Berry => "Beere",
}
.into()
}
pub fn plural(&self) -> String {
match self {
ItemType::Berry => "Beeren",
}
.into()
}
pub fn description(&self) -> String {
match self {
ItemType::Berry => "Von Pflanzen erntbar. Kann im Shop zum Einkaufen benutzt werden.",
}
.into()
}
}
#[derive(Component, Serialize, Deserialize, Clone)]
pub struct ItemStack {
pub item_type: ItemType,
pub amount: u32,
}
#[derive(Resource, Default, Serialize, Deserialize)]
pub struct Inventory {
pub items: Vec<Entity>,
}
#[derive(Component)]
pub enum RootMarker {
Inventory,
}
#[derive(Component)]
pub enum ButtonType {
InventoryOpen,
InventoryClose,
}

View File

@@ -0,0 +1,40 @@
use crate::{features::inventory::ui::open_inventory, prelude::*};
use components::*;
pub mod components;
pub mod ui;
pub struct InventoryPlugin;
impl Plugin for InventoryPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Inventory>();
app.add_systems(Update, buttons.run_if(in_state(AppState::GameScreen)));
}
}
fn buttons(
mut commands: Commands,
mut interaction_query: Query<(&Interaction, &ButtonType), (Changed<Interaction>, With<Button>)>,
itemstack_query: Query<&ItemStack>,
root_query: Query<(Entity, &RootMarker)>,
) {
for (interaction, button_type) in &mut interaction_query {
match *interaction {
Interaction::Pressed => match button_type {
ButtonType::InventoryOpen => {
open_inventory(&mut commands, itemstack_query);
}
ButtonType::InventoryClose => {
for (entity, root) in root_query.iter() {
match *root {
RootMarker::Inventory => commands.entity(entity).despawn(),
}
}
}
},
_ => {}
}
}
}

View File

@@ -0,0 +1,64 @@
use super::super::components::{ButtonType, RootMarker};
use crate::{features::inventory::ui::list_itemstack, prelude::*};
pub fn open_inventory(commands: &mut Commands, items: Query<&ItemStack>) {
commands
.spawn((
RootMarker::Inventory,
Node {
position_type: PositionType::Absolute,
width: percent(100),
height: percent(100),
..Node::center()
},
ZIndex(1),
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.8)),
))
.with_children(|parent| {
parent
.spawn((
Node {
padding: UiRect::all(px(20.0)),
..Node::vstack(px(0))
},
BackgroundColor(Color::srgb(0.2, 0.2, 0.2)),
BorderRadius::all(px(10.0)),
))
.with_children(|parent| {
parent.spawn((
Node {
width: percent(100.0),
justify_content: JustifyContent::SpaceBetween,
margin: UiRect::bottom(px(20.0)),
..Node::hstack(px(20))
},
children![
text("Inventar", 40.0, Color::WHITE),
pill_button(
ButtonType::InventoryClose,
ButtonVariant::Destructive,
Node {
width: px(40),
height: px(40),
..default()
},
"X",
24.0
),
],
));
parent
.spawn(Node {
width: percent(100),
margin: UiRect::top(px(10.0)),
..Node::vstack(px(10))
})
.with_children(|parent| {
for itemstack in items.iter() {
parent.spawn(list_itemstack(itemstack));
}
});
});
});
}

View File

@@ -0,0 +1,44 @@
use crate::prelude::*;
pub fn list_itemstack(itemstack: &ItemStack) -> impl Bundle {
let name = match itemstack.amount {
1 => itemstack.item_type.singular(),
_ => itemstack.item_type.plural(),
};
(
Node {
padding: UiRect::all(px(4)),
..Node::hstack(px(8))
},
BackgroundColor(ButtonVariant::Secondary.normal_background()),
BorderRadius::all(px(10)),
children![
(
// Placeholder for icon
Node {
height: percent(100),
aspect_ratio: Some(1.0),
..default()
},
BackgroundColor(ButtonVariant::Secondary.hover_background()),
BorderRadius::all(px(10))
),
(
Node {
justify_content: JustifyContent::Center,
padding: UiRect::vertical(px(4)),
..Node::vstack(px(4))
},
children![
text(
format!("{} ({})", name, itemstack.amount),
14.0,
Color::WHITE
),
text(itemstack.item_type.description(), 10.0, Color::WHITE)
]
)
],
)
}

View File

@@ -0,0 +1,5 @@
pub mod inventory;
pub mod item;
pub use inventory::*;
pub use item::*;

View File

@@ -1,13 +1,24 @@
pub mod config;
pub mod core; pub mod core;
pub mod game_screen; pub mod game_screen;
pub mod grid; pub mod grid;
pub mod hud;
pub mod input; pub mod input;
pub mod inventory;
pub mod phase;
pub mod pom; pub mod pom;
pub mod savegame;
pub mod start_screen; pub mod start_screen;
pub mod ui;
pub use core::CorePlugin; pub use core::CorePlugin;
pub use game_screen::GameScreenPlugin; pub use game_screen::GameScreenPlugin;
pub use grid::GridPlugin; pub use grid::GridPlugin;
pub use hud::HudPlugin;
pub use input::InputPlugin; pub use input::InputPlugin;
pub use inventory::InventoryPlugin;
pub use phase::PhasePlugin;
pub use pom::PomPlugin; pub use pom::PomPlugin;
pub use savegame::SavegamePlugin;
pub use start_screen::StartScreenPlugin; pub use start_screen::StartScreenPlugin;
pub use ui::UiPlugin;

View File

@@ -0,0 +1,65 @@
use super::utils::format_time;
use crate::prelude::*;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Phase {
Break { duration: f32 },
Focus { duration: f32 },
Paused { previous_phase: Box<Phase> },
Finished { completed_phase: Box<Phase> },
}
impl Phase {
pub fn ui_color(&self) -> Color {
match self {
Phase::Focus { .. } => Color::srgb(0.9, 0.3, 0.3),
Phase::Break { .. } => Color::srgb(0.3, 0.8, 0.5),
Phase::Paused { .. } => Color::srgb(0.5, 0.5, 0.5),
Phase::Finished { .. } => Color::srgb(0.9, 0.8, 0.2),
}
}
pub fn display_name(&self) -> &str {
match self {
Phase::Focus { .. } => "Fokus",
Phase::Break { .. } => "Pause",
Phase::Paused { .. } => "PAUSIERT [Leertaste]",
Phase::Finished { .. } => "ABGELAUFEN [Enter]",
}
}
pub fn format_duration(&self) -> String {
match self {
Phase::Focus { duration } | Phase::Break { duration } => format_time(*duration),
Phase::Paused { previous_phase } => previous_phase.format_duration(),
Phase::Finished { .. } => "00:00".to_string(),
}
}
}
#[derive(Resource, Debug, Serialize, Deserialize, Clone)]
pub struct CurrentPhase(pub Phase);
#[derive(Resource, Debug, Serialize, Deserialize, Clone)]
pub struct TimerSettings {
pub focus_duration: u32,
pub short_break_duration: u32,
pub long_break_duration: u32,
pub long_break_interval: u32,
}
impl Default for TimerSettings {
fn default() -> Self {
Self {
focus_duration: 25 * 60,
short_break_duration: 5 * 60,
long_break_duration: 15 * 60,
long_break_interval: 4,
}
}
}
#[derive(Resource, Debug, Default, Serialize, Deserialize, Clone)]
pub struct SessionTracker {
pub completed_focus_phases: u32,
}

View File

@@ -0,0 +1,12 @@
use crate::prelude::*;
#[derive(Message)]
pub struct PhaseTimerFinishedMessage {
pub phase: Phase,
}
#[derive(Message)]
pub struct PhaseTimerPauseMessage;
#[derive(Message)]
pub struct NextPhaseMessage;

161
src/features/phase/mod.rs Normal file
View File

@@ -0,0 +1,161 @@
use crate::features::savegame::messages::SavegameDumpMessage;
use crate::prelude::*;
use components::{SessionTracker, TimerSettings};
use messages::*;
pub mod components;
pub mod messages;
pub mod utils;
pub struct PhasePlugin;
impl Plugin for PhasePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<TimerSettings>();
app.init_resource::<SessionTracker>();
app.insert_resource(CurrentPhase(Phase::Focus {
duration: 25.0 * 60.0,
}));
app.add_message::<PhaseTimerFinishedMessage>();
app.add_systems(OnEnter(AppState::GameScreen), load_rules);
app.add_systems(
Update,
(tick_timer, handle_pause, handle_continue).run_if(in_state(AppState::GameScreen)),
);
#[cfg(debug_assertions)]
app.add_systems(Update, debug_short_phase_duration);
}
}
#[cfg(debug_assertions)]
fn debug_short_phase_duration(
mut phase_res: ResMut<CurrentPhase>,
keys: Res<ButtonInput<KeyCode>>,
) {
if keys.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight])
&& keys.just_pressed(KeyCode::Enter)
{
let phase = &mut phase_res.0;
match phase {
Phase::Focus { duration } | Phase::Break { duration } => {
*duration = 3.0;
println!("Debug: Phase duration set to 3 seconds!");
}
_ => {}
}
}
}
fn load_rules(mut phase_res: ResMut<CurrentPhase>, settings: Res<TimerSettings>) {
let phase = &mut phase_res.0;
let new_phase = match phase {
Phase::Focus { .. } => Some(Phase::Focus {
duration: settings.focus_duration as f32,
}),
Phase::Break { .. } => Some(Phase::Break { duration: 0.0 }),
_ => None,
};
if let Some(p) = new_phase {
*phase = p;
}
}
fn tick_timer(
time: Res<Time>,
mut phase_res: ResMut<CurrentPhase>,
mut finish_writer: MessageWriter<PhaseTimerFinishedMessage>,
mut savegame_messages: MessageWriter<SavegameDumpMessage>,
) {
let delta = time.delta_secs();
let phase = &mut phase_res.0;
match phase {
Phase::Focus { duration } | Phase::Break { duration } => {
*duration -= delta;
if *duration <= 0.0 {
finish_writer.write(PhaseTimerFinishedMessage {
phase: phase.clone(),
});
let completed = phase.clone();
*phase = Phase::Finished {
completed_phase: Box::new(completed),
};
println!("phase ended");
savegame_messages.write(SavegameDumpMessage);
}
}
_ => {}
}
}
fn handle_pause(
mut messages: MessageReader<PhaseTimerPauseMessage>,
mut phase_res: ResMut<CurrentPhase>,
) {
for _ in messages.read() {
let phase = &mut phase_res.0;
match phase {
Phase::Focus { .. } | Phase::Break { .. } => {
let current_state = phase.clone();
*phase = Phase::Paused {
previous_phase: Box::new(current_state),
};
println!("Phase paused");
}
Phase::Paused { previous_phase } => {
*phase = *previous_phase.clone();
println!("Phase resumed");
}
_ => {}
}
}
}
fn handle_continue(
mut messages: MessageReader<NextPhaseMessage>,
mut phase_res: ResMut<CurrentPhase>,
mut session_tracker: ResMut<SessionTracker>,
settings: Res<TimerSettings>,
) {
for _ in messages.read() {
let phase = &mut phase_res.0;
if let Phase::Finished { completed_phase } = phase {
match **completed_phase {
Phase::Focus { .. } => {
session_tracker.completed_focus_phases += 1;
// TODO: add berry grant logic
let is_long_break = session_tracker.completed_focus_phases > 0
&& session_tracker.completed_focus_phases % settings.long_break_interval
== 0;
if is_long_break {
*phase = Phase::Break {
duration: settings.long_break_duration as f32,
};
} else {
*phase = Phase::Break {
duration: settings.short_break_duration as f32,
};
}
}
Phase::Break { .. } => {
*phase = Phase::Focus {
duration: 25.0 * 60.0,
};
}
_ => {}
}
}
}
}

View File

@@ -0,0 +1,14 @@
pub fn format_time(seconds: f32) -> String {
let seconds = seconds.max(0.0) as u32;
if seconds >= 3600 {
let hours = seconds / 3600;
let minutes = (seconds % 3600) / 60;
let secs = seconds % 60;
format!("{:02}:{:02}:{:02}", hours, minutes, secs)
} else {
let minutes = seconds / 60;
let secs = seconds % 60;
format!("{:02}:{:02}", minutes, secs)
}
}

View File

@@ -1,11 +1,10 @@
use crate::prelude::*;
use std::collections::VecDeque; use std::collections::VecDeque;
use bevy::prelude::*;
#[derive(Component)] #[derive(Component)]
pub struct Pom; pub struct Pom;
#[derive(Component)] #[derive(Component, Serialize, Deserialize, Clone, Copy)]
pub struct GridPosition { pub struct GridPosition {
pub x: u32, pub x: u32,
pub y: u32, pub y: u32,

View File

@@ -1,4 +1,4 @@
use bevy::prelude::*; use crate::prelude::*;
#[derive(Message)] #[derive(Message)]
pub struct MoveMessage { pub struct MoveMessage {

View File

@@ -1,13 +1,11 @@
use crate::components::pom::{GridPosition, MovingState, PathQueue, Pom}; use crate::prelude::*;
use crate::components::tile::{Grid, TileState}; use components::*;
use crate::messages::{InvalidMoveMessage, MoveMessage}; use messages::InvalidMoveMessage;
use crate::plugins::grid::{GRID_WIDTH, grid_to_world_coords}; use utils::find_path;
use crate::states::*;
use crate::utils::pathfinding::find_path;
use bevy::prelude::*;
use bevy_aseprite_ultra::prelude::*;
const MOVE_SPEED: f32 = 2.0 * GRID_WIDTH as f32; pub mod components;
pub mod messages;
pub mod utils;
pub struct PomPlugin; pub struct PomPlugin;
@@ -23,7 +21,7 @@ impl Plugin for PomPlugin {
} }
} }
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { fn setup(mut commands: Commands, asset_server: Res<AssetServer>, config: Res<GameConfig>) {
commands.spawn(( commands.spawn((
Pom, Pom,
GridPosition { x: 0, y: 0 }, GridPosition { x: 0, y: 0 },
@@ -34,7 +32,13 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
animation: Animation::tag("sleep-sit-start").with_repeat(AnimationRepeat::Loop), animation: Animation::tag("sleep-sit-start").with_repeat(AnimationRepeat::Loop),
}, },
Sprite::default(), Sprite::default(),
Transform::from_translation(grid_to_world_coords(0, 0, Some(1.0))), Transform::from_translation(grid_to_world_coords(
0,
0,
Some(1.0),
config.grid_width,
config.grid_height,
)),
)); ));
} }
@@ -53,22 +57,20 @@ fn handle_move(
) { ) {
for message in move_messages.read() { for message in move_messages.read() {
for (grid_pos, mut path_queue) in pom_query.iter_mut() { for (grid_pos, mut path_queue) in pom_query.iter_mut() {
let start = (grid_pos.x, grid_pos.y); let grid_start = (grid_pos.x, grid_pos.y);
let start = path_queue.steps.front().unwrap_or(&grid_start);
let end = (message.x, message.y); let end = (message.x, message.y);
println!("{}, {}", end.0, end.1); match find_path(*start, end, &grid, &tile_query) {
match find_path(start, end, &grid, &tile_query) {
Some(new_path) => { Some(new_path) => {
path_queue.steps = new_path; path_queue.steps = new_path;
println!("Path found with {} steps", path_queue.steps.len());
} }
None => { None => {
let msg = format!( let msg = format!(
"Cannot move to ({}, {}). Path blocked or invalid.", "Cannot move to ({}, {}). Path blocked or invalid.",
message.x, message.y message.x, message.y
); );
println!("{}", msg); dbg!(&msg);
invalid_move_messages.write(InvalidMoveMessage { message: msg }); invalid_move_messages.write(InvalidMoveMessage { message: msg });
} }
} }
@@ -84,12 +86,20 @@ fn move_pom(
&mut PathQueue, &mut PathQueue,
&mut MovingState, &mut MovingState,
)>, )>,
config: Res<GameConfig>,
) { ) {
let dt = time.delta_secs(); let dt = time.delta_secs();
let move_speed = config.pom_speed * TILE_SIZE;
for (mut transform, mut grid_pos, mut path_queue, mut moving_state) in query.iter_mut() { for (mut transform, mut grid_pos, mut path_queue, mut moving_state) in query.iter_mut() {
if let Some(&target) = path_queue.steps.front() { if let Some(&target) = path_queue.steps.front() {
let target_pos = grid_to_world_coords(target.0, target.1, Some(1.0)); let target_pos = grid_to_world_coords(
target.0,
target.1,
Some(1.0),
config.grid_width,
config.grid_height,
);
let distance = transform.translation.distance(target_pos); let distance = transform.translation.distance(target_pos);
let dx = target.0 as i32 - grid_pos.x as i32; let dx = target.0 as i32 - grid_pos.x as i32;
@@ -102,14 +112,14 @@ fn move_pom(
_ => (), _ => (),
} }
if distance < MOVE_SPEED * dt { if distance < move_speed * dt {
transform.translation = target_pos; transform.translation = target_pos;
grid_pos.x = target.0; grid_pos.x = target.0;
grid_pos.y = target.1; grid_pos.y = target.1;
path_queue.steps.pop_front(); path_queue.steps.pop_front();
} else { } else {
let direction = (target_pos - transform.translation).normalize(); let direction = (target_pos - transform.translation).normalize();
transform.translation += direction * MOVE_SPEED * dt; transform.translation += direction * move_speed * dt;
} }
} else { } else {
*moving_state = MovingState::Idle; *moving_state = MovingState::Idle;

View File

@@ -1,5 +1,4 @@
use crate::components::tile::{Grid, TileState}; use crate::prelude::*;
use bevy::prelude::*;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, VecDeque}; use std::collections::{BinaryHeap, HashMap, VecDeque};
@@ -27,7 +26,7 @@ impl PartialOrd for Node {
} }
pub fn manhattan_distance(x1: u32, y1: u32, x2: u32, y2: u32) -> u32 { pub fn manhattan_distance(x1: u32, y1: u32, x2: u32, y2: u32) -> u32 {
(x1 as i32 - x2 as i32).abs() as u32 + (y1 as i32 - y2 as i32).abs() as u32 x1.abs_diff(x2) + y1.abs_diff(y2)
} }
pub fn find_path( pub fn find_path(
@@ -36,11 +35,10 @@ pub fn find_path(
grid: &Grid, grid: &Grid,
tile_query: &Query<&TileState>, tile_query: &Query<&TileState>,
) -> Option<VecDeque<(u32, u32)>> { ) -> Option<VecDeque<(u32, u32)>> {
println!("find_path");
let target_entity = grid.get_tile(end).ok()?; let target_entity = grid.get_tile(end).ok()?;
let state = tile_query.get(target_entity).unwrap(); let target_state = tile_query.get(target_entity).ok()?;
if (*state).is_blocking() {
if target_state.is_blocking() {
return None; return None;
} }
@@ -66,9 +64,16 @@ pub fn find_path(
path.push_front(curr); path.push_front(curr);
curr = *came_from.get(&curr).unwrap(); curr = *came_from.get(&curr).unwrap();
} }
path.push_front(start);
return Some(path); return Some(path);
} }
if let Some(&best_g) = g_score.get(&current_pos) {
if current.cost > best_g {
continue;
}
}
let neighbors = [ let neighbors = [
(current.x as i32 + 1, current.y as i32), (current.x as i32 + 1, current.y as i32),
(current.x as i32 - 1, current.y as i32), (current.x as i32 - 1, current.y as i32),
@@ -82,9 +87,12 @@ pub fn find_path(
} }
let next_pos = (nx as u32, ny as u32); let next_pos = (nx as u32, ny as u32);
let tile_entity = grid.get_tile(next_pos).ok()?; let tile_entity = match grid.get_tile(next_pos) {
let state = tile_query.get(tile_entity).unwrap(); Ok(e) => e,
if (*state).is_blocking() { Err(_) => continue,
};
let state = tile_query.get(tile_entity).ok()?;
if state.is_blocking() {
continue; continue;
} }
@@ -92,6 +100,7 @@ pub fn find_path(
if tentative_g_score < *g_score.get(&next_pos).unwrap_or(&u32::MAX) { if tentative_g_score < *g_score.get(&next_pos).unwrap_or(&u32::MAX) {
came_from.insert(next_pos, current_pos); came_from.insert(next_pos, current_pos);
g_score.insert(next_pos, tentative_g_score); g_score.insert(next_pos, tentative_g_score);
open_set.push(Node { open_set.push(Node {
x: next_pos.0, x: next_pos.0,
y: next_pos.1, y: next_pos.1,

View File

@@ -0,0 +1,106 @@
use crate::prelude::*;
use std::fs;
use std::path::PathBuf;
#[derive(Resource, Clone, Debug)]
pub struct SavegamePath(pub PathBuf);
#[derive(Debug)]
pub struct SavegameInfo {
pub path: SavegamePath,
pub index: u32,
pub total_berries: u32,
pub completed_focus: u32,
}
#[derive(Deserialize)]
struct PartialSaveData {
session_tracker: PartialSessionTracker,
}
#[derive(Deserialize)]
struct PartialSessionTracker {
completed_focus_phases: u32,
}
impl SavegamePath {
pub fn new(index: u32) -> Self {
let base_path = get_internal_path().unwrap_or_else(|| {
println!(
"Could not determine platform-specific save directory. Falling back to `./saves/"
);
PathBuf::from("./saves/")
});
if let Err(e) = std::fs::create_dir_all(&base_path) {
panic!("Failed to create save directory at {:?}: {}", base_path, e);
}
Self(base_path.join(format!("savegame-{}.json", index)))
}
pub fn list() -> Vec<SavegameInfo> {
let mut savegames = Vec::new();
let Some(base_path) = get_internal_path() else {
return Vec::new();
};
if !base_path.exists() {
return Vec::new();
}
let Ok(entries) = fs::read_dir(base_path) else {
return Vec::new();
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
let Some(file_name) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if !file_name.starts_with("savegame-") {
continue;
}
let Ok(index) = file_name.trim_start_matches("savegame-").parse::<u32>() else {
continue;
};
let Ok(content) = fs::read_to_string(&path) else {
continue;
};
let Ok(data) = serde_json::from_str::<PartialSaveData>(&content) else {
continue;
};
savegames.push(SavegameInfo {
path: SavegamePath(path),
index,
total_berries: 0, // TODO: add total_berries
completed_focus: data.session_tracker.completed_focus_phases,
});
}
savegames.sort_by_key(|s| s.index);
savegames
}
pub fn next() -> Self {
let savegames = Self::list();
let next_index = savegames.last().map(|s| s.index + 1).unwrap_or(0);
Self::new(next_index)
}
}
#[derive(Component)]
pub enum RootMarker {
PopupSavegameLoad,
}
#[derive(Component)]
pub enum ButtonType {
SavegameLoad { savegame_path: SavegamePath },
SavegameDelete { savegame_path: SavegamePath },
PopupClose,
}

View File

@@ -0,0 +1,7 @@
use crate::prelude::*;
#[derive(Message)]
pub struct SavegameDumpMessage;
#[derive(Message)]
pub struct SavegameLoadMessage;

View File

@@ -0,0 +1,173 @@
use crate::features::phase::components::{SessionTracker, TimerSettings};
use crate::features::savegame::ui::load_popup_handler;
use crate::prelude::*;
use messages::*;
use std::fs::File;
use std::io::{Read, Write};
pub mod components;
pub mod messages;
pub mod ui;
pub struct SavegamePlugin;
impl Plugin for SavegamePlugin {
fn build(&self, app: &mut App) {
app.add_message::<SavegameDumpMessage>();
app.add_message::<SavegameLoadMessage>();
app.add_systems(Update, dump_savegame.run_if(in_state(AppState::GameScreen)));
app.add_systems(Update, load_savegame.run_if(in_state(AppState::GameScreen)));
app.add_systems(Update, load_popup_handler);
}
}
#[derive(Serialize, Deserialize)]
struct SaveData {
grid_width: u32,
grid_height: u32,
tiles: Vec<Vec<TileState>>,
current_phase: CurrentPhase,
session_tracker: SessionTracker,
timer_settings: TimerSettings,
pom_position: GridPosition,
inventory: Vec<ItemStack>,
}
fn dump_savegame(
mut messages: MessageReader<SavegameDumpMessage>,
save_path: Res<SavegamePath>,
grid: Res<Grid>,
tile_query: Query<&TileState>,
phase: Res<CurrentPhase>,
tracker: Res<SessionTracker>,
settings: Res<TimerSettings>,
pom_query: Query<&GridPosition, With<Pom>>,
inventory: Res<Inventory>,
item_query: Query<&ItemStack>,
) {
for _ in messages.read() {
let mut tile_states = Vec::new();
for x in 0..grid.width {
let mut col = Vec::new();
for y in 0..grid.height {
if let Ok(entity) = grid.get_tile((x, y)) {
if let Ok(state) = tile_query.get(entity) {
col.push(*state);
} else {
col.push(TileState::Unclaimed);
}
} else {
col.push(TileState::Unclaimed);
}
}
tile_states.push(col);
}
let pom_pos = pom_query.single().unwrap();
let item_stacks: Vec<ItemStack> = inventory
.items
.iter()
.filter_map(|entity| item_query.get(*entity).ok().cloned())
.collect();
let save_data = SaveData {
grid_width: grid.width,
grid_height: grid.height,
tiles: tile_states,
current_phase: phase.clone(),
session_tracker: tracker.clone(),
timer_settings: settings.clone(),
pom_position: *pom_pos,
inventory: item_stacks,
};
match serde_json::to_string_pretty(&save_data) {
Ok(serialized) => {
if let Ok(mut file) = File::create(&save_path.0) {
if let Err(e) = file.write_all(serialized.as_bytes()) {
panic!("Failed to write save file: {}", e);
} else {
println!("Game saved to {}", save_path.0.display());
}
} else {
panic!("Failed to create save file at {}", save_path.0.display());
}
}
Err(e) => {
panic!("Failed to serialize save data: {}", e);
}
}
}
}
fn load_savegame(
mut commands: Commands,
mut messages: MessageReader<SavegameLoadMessage>,
save_path: Res<SavegamePath>,
grid: Res<Grid>,
mut tile_query: Query<&mut TileState>,
mut phase: ResMut<CurrentPhase>,
mut tracker: ResMut<SessionTracker>,
mut settings: ResMut<TimerSettings>,
mut pom_query: Query<(&mut GridPosition, &mut Transform), With<Pom>>,
mut inventory: ResMut<Inventory>,
) {
for _ in messages.read() {
if let Ok(mut file) = File::open(&save_path.0) {
let mut content = String::new();
if let Err(e) = file.read_to_string(&mut content) {
eprintln!("Failed to read save file: {}", e);
continue;
}
match serde_json::from_str::<SaveData>(&content) {
Ok(save_data) => {
*phase = save_data.current_phase;
*tracker = save_data.session_tracker;
*settings = save_data.timer_settings;
if let Ok((mut pom_pos, mut pom_transform)) = pom_query.single_mut() {
*pom_pos = save_data.pom_position;
pom_transform.translation = grid_to_world_coords(
save_data.pom_position.x,
save_data.pom_position.y,
Some(1.0),
save_data.grid_width,
save_data.grid_height,
)
}
for x in 0..save_data.grid_width {
for y in 0..save_data.grid_height {
if x < grid.width && y < grid.height {
if let Ok(entity) = grid.get_tile((x, y)) {
if let Ok(mut state) = tile_query.get_mut(entity) {
*state = save_data.tiles[x as usize][y as usize];
}
}
}
}
}
let stack_entities: Vec<Entity> = save_data
.inventory
.iter()
.map(|stack| commands.spawn(stack.clone()).id())
.collect();
inventory.items = stack_entities;
println!("Game loaded from {}", save_path.0.display());
}
Err(e) => {
eprintln!("Failed to parse save data: {}", e);
}
}
} else {
eprintln!("Failed to open save file at {}", save_path.0.display());
}
}
}

View File

@@ -0,0 +1,162 @@
use super::super::components::{ButtonType, RootMarker};
use crate::{features::savegame::messages::SavegameLoadMessage, prelude::*};
pub fn spawn_load_popup(commands: &mut Commands) {
commands
.spawn((
RootMarker::PopupSavegameLoad,
Node {
position_type: PositionType::Absolute,
width: percent(100),
height: percent(100),
..Node::center()
},
ZIndex(1),
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.8)),
))
.with_children(|parent| {
parent
.spawn((
Node {
width: px(600.0),
height: px(500.0),
padding: UiRect::all(px(20.0)),
align_items: AlignItems::Center,
..Node::vstack(px(10))
},
BackgroundColor(Color::srgb(0.2, 0.2, 0.2)),
BorderRadius::all(px(10.0)),
))
.with_children(|parent| {
parent.spawn((
Node {
width: percent(100.0),
justify_content: JustifyContent::SpaceBetween,
align_items: AlignItems::Center,
margin: UiRect::bottom(px(20.0)),
..default()
},
children![
text("Spielstand Auswahl", 40.0, Color::WHITE),
pill_button(
ButtonType::PopupClose,
ButtonVariant::Destructive,
Node {
width: px(40),
height: px(40),
..default()
},
"X",
24.0
)
],
));
parent
.spawn(Node {
width: percent(100),
flex_direction: FlexDirection::Column,
overflow: Overflow::scroll_y(),
margin: UiRect::all(px(20.0)),
row_gap: px(10.0),
..default()
})
.with_children(|parent| {
for savegame in SavegamePath::list() {
parent.spawn((
Button,
ButtonType::SavegameLoad {
savegame_path: savegame.path.clone(),
},
ButtonVariant::Secondary,
Node {
width: percent(100),
height: px(80),
flex_direction: FlexDirection::Row,
column_gap: px(10.0),
padding: UiRect::horizontal(px(10.0)),
..Node::center()
},
BackgroundColor(ButtonVariant::Secondary.normal_background()),
BorderRadius::all(px(10)),
children![
(
Node {
width: percent(100),
height: percent(100),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
..default()
},
children![
text(
format!("Spielstand {}", savegame.index + 1),
24.0,
Color::WHITE
),
text(
format!(
"Beeren: {}, Fokusphasen abgeschlossen: {}",
savegame.total_berries,
savegame.completed_focus
),
18.0,
Color::WHITE,
),
]
),
pill_button(
ButtonType::SavegameDelete {
savegame_path: savegame.path.clone()
},
ButtonVariant::Destructive,
Node {
width: px(40),
height: px(40),
..default()
},
"X",
24.0
),
],
));
}
});
});
});
}
pub fn load_popup_handler(
mut commands: Commands,
mut next_state: ResMut<NextState<AppState>>,
mut interaction_query: Query<(&Interaction, &ButtonType), (Changed<Interaction>, With<Button>)>,
root_query: Query<(Entity, &RootMarker)>,
mut savegame_messages: MessageWriter<SavegameLoadMessage>,
) {
for (interaction, button_type) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
match button_type {
ButtonType::PopupClose => {}
ButtonType::SavegameLoad { savegame_path } => {
commands.insert_resource(savegame_path.clone());
next_state.set(AppState::GameScreen);
savegame_messages.write(SavegameLoadMessage);
}
ButtonType::SavegameDelete { savegame_path } => {
if let Err(e) = std::fs::remove_file(savegame_path.clone().0) {
println!("Error while deleting savegame: {:?}", e);
}
}
};
for (entity, root) in root_query.iter() {
match *root {
RootMarker::PopupSavegameLoad => commands.entity(entity).despawn(),
}
}
}
_ => (),
}
}
}

View File

@@ -0,0 +1,3 @@
pub mod load;
pub use load::*;

View File

@@ -0,0 +1,13 @@
use crate::prelude::*;
#[derive(Component)]
pub enum RootMarker {
MainMenu,
}
#[derive(Component)]
pub enum ButtonType {
LoadGame,
NewGame,
Settings,
}

View File

@@ -0,0 +1,94 @@
use crate::features::savegame::ui::spawn_load_popup;
use crate::prelude::*;
use components::*;
pub mod components;
pub struct StartScreenPlugin;
impl Plugin for StartScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::StartScreen), setup);
app.add_systems(OnExit(AppState::StartScreen), cleanup);
app.add_systems(Update, menu.run_if(in_state(AppState::StartScreen)));
}
}
fn setup(mut commands: Commands) {
commands.spawn((
RootMarker::MainMenu,
Node {
width: percent(100),
height: percent(100),
flex_direction: FlexDirection::Column,
row_gap: px(10),
..Node::center()
},
children![
text("Pomomon Garden", 64.0, Color::WHITE),
button(
ButtonType::LoadGame,
ButtonVariant::Primary,
Node {
width: px(280),
padding: UiRect::all(px(10)),
..default()
},
"Spiel laden",
33.0
),
button(
ButtonType::NewGame,
ButtonVariant::Primary,
Node {
width: px(280),
padding: UiRect::all(px(10)),
..default()
},
"Neues Spiel",
33.0,
),
button(
ButtonType::Settings,
ButtonVariant::Secondary,
Node {
width: px(280),
padding: UiRect::all(px(10)),
..default()
},
"Einstellungen",
33.0
),
],
));
}
fn menu(
mut commands: Commands,
mut next_state: ResMut<NextState<AppState>>,
mut interaction_query: Query<(&Interaction, &ButtonType), (Changed<Interaction>, With<Button>)>,
) {
for (interaction, button_type) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
match button_type {
ButtonType::LoadGame => {
spawn_load_popup(&mut commands);
}
ButtonType::NewGame => {
commands.insert_resource(SavegamePath::next());
next_state.set(AppState::GameScreen);
}
ButtonType::Settings => todo!(),
};
}
_ => (),
}
}
}
fn cleanup(mut commands: Commands, query: Query<Entity, With<RootMarker>>) {
for entity in query.iter() {
commands.entity(entity).despawn();
}
}

View File

@@ -0,0 +1,48 @@
use crate::prelude::*;
#[derive(EntityEvent, Debug)]
#[entity_event(propagate, auto_propagate)]
pub struct Scroll {
pub entity: Entity,
pub delta: Vec2,
}
#[derive(Component, Clone)]
pub enum ButtonVariant {
Primary,
Secondary,
Destructive,
}
impl ButtonVariant {
pub fn normal_background(&self) -> Color {
match self {
ButtonVariant::Primary => Color::srgb(0.35, 0.17, 0.78),
ButtonVariant::Secondary => Color::srgb(0.15, 0.15, 0.15),
ButtonVariant::Destructive => Color::srgb(0.79, 0.17, 0.20),
}
}
pub fn hover_background(&self) -> Color {
match self {
ButtonVariant::Primary => Color::srgb(0.45, 0.27, 0.88),
ButtonVariant::Secondary => Color::srgb(0.25, 0.25, 0.25),
ButtonVariant::Destructive => Color::srgb(0.89, 0.27, 0.30),
}
}
pub fn pressed_background(&self) -> Color {
match self {
ButtonVariant::Primary => Color::srgb(0.55, 0.37, 0.98),
ButtonVariant::Secondary => Color::srgb(0.35, 0.35, 0.35),
ButtonVariant::Destructive => Color::srgb(0.99, 0.37, 0.40),
}
}
pub fn text_color(&self) -> Color {
match self {
ButtonVariant::Primary | ButtonVariant::Destructive => Color::srgb(0.1, 0.1, 0.1),
ButtonVariant::Secondary => Color::WHITE,
}
}
}

View File

@@ -0,0 +1,6 @@
use crate::prelude::*;
pub const LINE_HEIGHT: f32 = 21.0;
pub const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
pub const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
pub const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);

89
src/features/ui/mod.rs Normal file
View File

@@ -0,0 +1,89 @@
use crate::prelude::{button::update_buttons, *};
use bevy::{input::mouse::*, picking::hover::HoverMap};
pub mod components;
pub mod consts;
pub mod ui;
pub struct UiPlugin;
impl Plugin for UiPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, scroll_events);
app.add_observer(on_scroll_handler);
app.add_systems(Update, update_buttons);
}
}
fn scroll_events(
mut mouse_wheel_reader: MessageReader<MouseWheel>,
hover_map: Res<HoverMap>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut commands: Commands,
) {
for mouse_wheel in mouse_wheel_reader.read() {
let mut delta = -Vec2::new(mouse_wheel.x, mouse_wheel.y);
if mouse_wheel.unit == MouseScrollUnit::Line {
delta *= LINE_HEIGHT;
}
if keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) {
std::mem::swap(&mut delta.x, &mut delta.y);
}
for pointer_map in hover_map.values() {
for entity in pointer_map.keys().copied() {
commands.trigger(components::Scroll { entity, delta });
}
}
}
}
fn on_scroll_handler(
mut scroll: On<components::Scroll>,
mut query: Query<(&mut ScrollPosition, &Node, &ComputedNode)>,
) {
let Ok((mut scroll_position, node, computed)) = query.get_mut(scroll.entity) else {
return;
};
let max_offset = (computed.content_size() - computed.size()) * computed.inverse_scale_factor();
let delta = &mut scroll.delta;
if node.overflow.x == OverflowAxis::Scroll && delta.x != 0. {
// Is this node already scrolled all the way in the direction of the scroll?
let max = if delta.x > 0. {
scroll_position.x >= max_offset.x
} else {
scroll_position.x <= 0.
};
if !max {
scroll_position.x += delta.x;
// Consume the X portion of the scroll delta.
delta.x = 0.;
}
}
if node.overflow.y == OverflowAxis::Scroll && delta.y != 0. {
// Is this node already scrolled all the way in the direction of the scroll?
let max = if delta.y > 0. {
scroll_position.y >= max_offset.y
} else {
scroll_position.y <= 0.
};
if !max {
scroll_position.y += delta.y;
// Consume the Y portion of the scroll delta.
delta.y = 0.;
}
}
// Stop propagating when the delta is fully consumed.
if *delta == Vec2::ZERO {
scroll.propagate(false);
}
}

View File

@@ -0,0 +1,59 @@
use crate::prelude::*;
pub fn button(
button_type: impl Component,
variant: ButtonVariant,
mut node: Node,
title: impl Into<String>,
font_size: f32,
) -> impl Bundle {
node.justify_content = JustifyContent::Center;
node.align_items = AlignItems::Center;
(
Button,
button_type,
variant.clone(),
node,
BackgroundColor(variant.normal_background()),
BorderRadius::all(px(10)),
children![text(title, font_size, variant.text_color())],
)
}
pub fn pill_button(
button_type: impl Component,
variant: ButtonVariant,
mut node: Node,
title: impl Into<String>,
font_size: f32,
) -> impl Bundle {
node.justify_content = JustifyContent::Center;
node.align_items = AlignItems::Center;
(
Button,
button_type,
variant.clone(),
node,
BackgroundColor(variant.normal_background()),
BorderRadius::MAX,
children![text(title, font_size, variant.text_color())],
)
}
pub fn update_buttons(
mut interaction_query: Query<
(&Interaction, &ButtonVariant, &mut BackgroundColor),
(Changed<Interaction>, With<Button>),
>,
) {
for (interaction, variant, mut color) in &mut interaction_query {
*color = match *interaction {
Interaction::None => variant.normal_background(),
Interaction::Hovered => variant.hover_background(),
Interaction::Pressed => variant.pressed_background(),
}
.into()
}
}

View File

@@ -0,0 +1,33 @@
use crate::prelude::*;
pub trait Flexbox {
fn hstack(spacing: Val) -> Self;
fn vstack(spacing: Val) -> Self;
fn center() -> Self;
}
impl Flexbox for Node {
fn hstack(spacing: Val) -> Self {
Self {
flex_direction: FlexDirection::Row,
column_gap: spacing,
..default()
}
}
fn vstack(spacing: Val) -> Self {
Self {
flex_direction: FlexDirection::Column,
row_gap: spacing,
..default()
}
}
fn center() -> Self {
Self {
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
}
}
}

View File

@@ -0,0 +1,7 @@
pub mod button;
pub mod flexbox;
pub mod texts;
pub use button::{button, pill_button};
pub use flexbox::Flexbox;
pub use texts::{text, text_with_component};

View File

@@ -0,0 +1,19 @@
pub use crate::prelude::*;
pub fn text(content: impl Into<String>, size: f32, color: Color) -> (Text, TextFont, TextColor) {
(
Text::new(content),
TextFont::from_font_size(size),
TextColor(color),
)
}
pub fn text_with_component(
component: impl Component,
content: impl Into<String>,
size: f32,
color: Color,
) -> impl Bundle {
let (a, b, c) = text(content, size, color);
(component, a, b, c)
}

View File

@@ -1,6 +1,3 @@
pub mod components; pub mod features;
pub mod errors; pub mod prelude;
pub mod messages;
pub mod plugins;
pub mod states;
pub mod utils; pub mod utils;

View File

@@ -1,9 +1,9 @@
use bevy::prelude::*;
use bevy_aseprite_ultra::prelude::*;
use bevy_dev_tools::fps_overlay::*; use bevy_dev_tools::fps_overlay::*;
use pomomon_garden::plugins; use pomomon_garden::prelude::*;
fn main() { fn main() {
let config = GameConfig::read_config().unwrap_or(GameConfig::default());
App::new() App::new()
.add_plugins(( .add_plugins((
DefaultPlugins.set(ImagePlugin::default_nearest()), DefaultPlugins.set(ImagePlugin::default_nearest()),
@@ -22,12 +22,18 @@ fn main() {
}, },
},)) },))
.add_plugins(( .add_plugins((
plugins::CorePlugin, features::CorePlugin,
plugins::StartScreenPlugin, features::StartScreenPlugin,
plugins::GameScreenPlugin, features::GameScreenPlugin,
plugins::GridPlugin, features::GridPlugin,
plugins::PomPlugin, features::PomPlugin,
plugins::InputPlugin, features::InputPlugin,
features::PhasePlugin,
features::HudPlugin,
features::SavegamePlugin,
features::UiPlugin,
features::InventoryPlugin,
)) ))
.insert_resource(config)
.run(); .run();
} }

View File

@@ -1,19 +0,0 @@
use crate::states::*;
use bevy::prelude::*;
pub struct GameScreenPlugin;
impl Plugin for GameScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::GameScreen), setup);
app.add_systems(OnExit(AppState::GameScreen), cleanup);
}
}
fn setup(mut commands: Commands) {
commands.insert_resource(ClearColor(Color::srgb(0.294, 0.412, 0.184)));
}
fn cleanup(mut commands: Commands) {
commands.remove_resource::<ClearColor>();
}

View File

@@ -1,146 +0,0 @@
use crate::states::*;
use bevy::prelude::*;
pub struct StartScreenPlugin;
impl Plugin for StartScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::StartScreen), setup);
app.add_systems(OnExit(AppState::StartScreen), cleanup);
app.add_systems(Update, menu.run_if(in_state(AppState::StartScreen)));
}
}
#[derive(Resource)]
struct MenuData {
button_entity: Entity,
}
#[derive(Component)]
enum ButtonType {
LoadGame,
NewGame,
Settings,
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
fn setup(mut commands: Commands) {
let button_entity = commands
.spawn((
Node {
width: percent(100),
height: percent(100),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
..default()
},
children![
(
Text::new("Pomonon Garten"),
TextFont {
font_size: 64.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9))
),
(
Button,
ButtonType::LoadGame,
Node {
width: px(300),
height: px(65),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Spiel laden"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9))
)]
),
(
Button,
ButtonType::NewGame,
Node {
width: px(300),
height: px(65),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Neues Spiel"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9))
)]
),
(
Button,
ButtonType::Settings,
Node {
width: px(300),
height: px(65),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Einstellungen"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9))
)]
)
],
))
.id();
commands.insert_resource(MenuData { button_entity });
}
fn menu(
mut next_state: ResMut<NextState<AppState>>,
mut interaction_query: Query<
(&Interaction, &ButtonType, &mut BackgroundColor),
(Changed<Interaction>, With<Button>),
>,
) {
for (interaction, button_type, mut color) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
*color = PRESSED_BUTTON.into();
match button_type {
ButtonType::NewGame => next_state.set(AppState::GameScreen),
_ => (),
};
}
Interaction::Hovered => {
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
*color = NORMAL_BUTTON.into();
}
}
}
}
fn cleanup(mut commands: Commands, menu_data: Res<MenuData>) {
commands.entity(menu_data.button_entity).despawn();
}

22
src/prelude.rs Normal file
View File

@@ -0,0 +1,22 @@
pub use crate::features;
pub use crate::features::{
config::components::GameConfig,
core::states::AppState,
grid::{
components::{Grid, Tile, TileState},
consts::TILE_SIZE,
utils::{grid_to_world_coords, world_to_grid_coords},
},
inventory::components::{Inventory, ItemStack, ItemType},
phase::components::{CurrentPhase, Phase},
pom::{
components::{GridPosition, MovingState, Pom},
messages::{InteractStartMessage, MoveMessage},
},
savegame::components::SavegamePath,
ui::{components::ButtonVariant, consts::*, ui::*},
};
pub use crate::utils::path::get_internal_path;
pub use bevy::prelude::*;
pub use bevy_aseprite_ultra::prelude::*;
pub use serde::{Deserialize, Serialize};

View File

@@ -1,8 +0,0 @@
use bevy::prelude::*;
#[derive(States, Clone, PartialEq, Eq, Debug, Hash, Default, Reflect)]
pub enum AppState {
#[default]
StartScreen,
GameScreen,
}

View File

@@ -1 +1 @@
pub mod pathfinding; pub mod path;

12
src/utils/path.rs Normal file
View File

@@ -0,0 +1,12 @@
use directories::ProjectDirs;
use std::path::PathBuf;
pub fn get_internal_path() -> Option<PathBuf> {
let project_dirs = ProjectDirs::from("de", "demenik", "pomomon-garden");
if let Some(dirs) = project_dirs {
Some(dirs.data_local_dir().to_path_buf())
} else {
None
}
}