Skip to content

Commit

Permalink
Merge pull request #119 from red-life-project/issue63-logging
Browse files Browse the repository at this point in the history
player icon and logging
  • Loading branch information
Flippchen authored Nov 24, 2022
2 parents f228523 + 821265e commit b5aa197
Show file tree
Hide file tree
Showing 16 changed files with 150 additions and 67 deletions.
Binary file modified assets/player.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions game/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ serde = "1.0.145"
serde_yaml = "0.9.13"
ggez = "0.8.1"
dyn-clone = "1.0.9"
tracing = "0.1.37"
tracing-subscriber = "0.3.16"
fastrand = "1.8.0"
chrono = "0.4.23"

[build-dependencies]
fs_extra = "1.2.0"
Expand Down
5 changes: 5 additions & 0 deletions game/src/backend/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::backend::screen::StackCommand;
use ggez::GameError;
use std::io;
use std::sync::mpsc::SendError;
use tracing::error;

#[warn(clippy::enum_variant_names)]
#[derive(Debug)]
Expand All @@ -14,24 +15,28 @@ pub enum RLError {

impl From<GameError> for RLError {
fn from(e: GameError) -> Self {
error!("GameError: {}", e);
RLError::Ui(e)
}
}

impl From<serde_yaml::Error> for RLError {
fn from(e: serde_yaml::Error) -> Self {
error!("Deserialization Error: {}", e);
RLError::Deserialization(e)
}
}

impl From<io::Error> for RLError {
fn from(e: io::Error) -> Self {
error!("IO Error: {}", e);
RLError::IO(e)
}
}

impl From<SendError<StackCommand>> for RLError {
fn from(value: SendError<StackCommand>) -> Self {
error!("Could not send StackCommand: {}", value);
RLError::IO(io::Error::new(
io::ErrorKind::Other,
format!("Could not send StackCommand: {}", value),
Expand Down
22 changes: 15 additions & 7 deletions game/src/backend/gamestate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use std::collections::HashMap;
use std::fs;
use std::fs::read_dir;
use std::sync::mpsc::Sender;
use tracing::info;

const RESOURCE_POSITION: [f32; 3] = [316.0, 639.0, 1373.0];
const RESOURCE_NAME: [&str; 3] = ["Luft", "Energie", "Leben"];
Expand Down Expand Up @@ -48,6 +49,7 @@ impl PartialEq for GameState {

impl GameState {
pub fn new(ctx: &mut Context) -> RLResult<Self> {
info!("Creating new gamestate");
let mut result = GameState::default();
result.load_assets(ctx)?;
Ok(result)
Expand Down Expand Up @@ -142,6 +144,7 @@ impl GameState {
}
/// Loads the assets. Has to be called before drawing the game.
pub(crate) fn load_assets(&mut self, ctx: &mut Context) -> RLResult {
info!("Loading assets");
read_dir("assets")?.for_each(|file| {
let file = file.unwrap();
let bytes = fs::read(file.path()).unwrap();
Expand All @@ -163,17 +166,21 @@ impl GameState {
fs::create_dir_all("./saves")?;
if milestone {
fs::write("./saves/milestone.yaml", save_data)?;
info!("Saved gamestate as milestone");
} else {
fs::write("./saves/autosave.yaml", save_data)?;
info!("Saved gamestate as autosave");
}
Ok(())
}
/// Loads a game state from a file. The boolean value "milestone" determines whether this is a milestone or an autosave.
/// If the file doesn't exist, it will return a default game state.
pub fn load(milestone: bool) -> RLResult<GameState> {
let save_data = if milestone {
info!("Loading milestone...");
fs::read_to_string("./saves/milestone.yaml")
} else {
info!("Loading autosave...");
fs::read_to_string("./saves/autosave.yaml")
}?;
let game_state: GameState = serde_yaml::from_str(&save_data)?;
Expand All @@ -188,10 +195,10 @@ impl GameState {

/// Returns if the player would collide with a border if they moved in the given direction
fn border_collision_detection(next_player_pos: (usize, usize)) -> bool {
next_player_pos.0 >= 1785
|| next_player_pos.1 >= 896
|| next_player_pos.0 <= 280
|| next_player_pos.1 <= 225
next_player_pos.0 >= 1750 // Right border
|| next_player_pos.1 >= 850 // Bottom border
|| next_player_pos.0 <= 255 // Left border
|| next_player_pos.1 <= 220 // Top border
}
/// Returns a boolean indicating whether the player would collide with a machine or border if they moved in the given direction
///
Expand Down Expand Up @@ -223,6 +230,7 @@ impl GameState {
.all(|machine| running_machine.contains(&machine.to_string()))
{
self.player.milestone += 1;
info!("Player reached milestone {}", self.player.milestone);
self.save(true).unwrap();
}
}
Expand Down Expand Up @@ -292,7 +300,7 @@ mod test {

#[test]
fn test_gamestate() {
let gamestate = GameState::default();
let _gamestate = GameState::default();
}

#[test]
Expand All @@ -310,12 +318,12 @@ mod test {
#[test]
fn test_load_autosave() {
GameState::default().save(false).unwrap();
let gamestate_loaded = GameState::load(false).unwrap();
let _gamestate_loaded = GameState::load(false).unwrap();
}

#[test]
fn test_load_milestone() {
GameState::default().save(true).unwrap();
let gamestate_loaded = GameState::load(true).unwrap();
let _gamestate_loaded = GameState::load(true).unwrap();
}
}
7 changes: 5 additions & 2 deletions game/src/backend/movement.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use crate::backend::gamestate::GameState;
use crate::backend::screen::StackCommand;

use crate::RLResult;
use ggez::winit::event::VirtualKeyCode;
use ggez::Context;
use tracing::info;

const MOVEMENT_SPEED: usize = 5;
const MOVEMENT_SPEED: usize = 10;

impl GameState {
pub fn move_player(&mut self, ctx: &mut Context) -> RLResult {
let keys = ctx.keyboard.pressed_keys();
for key in keys.iter() {
match key {
VirtualKeyCode::Escape => {
info!("Escape pressed");
self.save(false)?;
self.screen_sender
.as_mut()
Expand Down Expand Up @@ -56,7 +59,7 @@ impl GameState {
}
// TODO: Interact with the possible area
VirtualKeyCode::E => {
dbg!(self.get_interactable());
info!("In interaction area: {:?}", self.get_interactable());
}
_ => {}
}
Expand Down
8 changes: 7 additions & 1 deletion game/src/backend/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ use crate::backend::utils::get_scale;
use crate::error::RLError;
use crate::main_menu::mainmenu::MainMenu;
use crate::{draw, RLResult};
use ggez::conf::FullscreenType::True;

use ggez::glam::vec2;
use ggez::graphics::Color;
use ggez::{event, graphics, Context};
use std::fmt::Debug;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::time::Instant;
use tracing::info;

/// A screen is every drawable object in the game, so the main menu is a screen too
pub trait Screen: Debug {
Expand Down Expand Up @@ -38,15 +39,19 @@ pub struct Popup {
}
impl Popup {
pub fn nasa(text: String) -> Self {
info!("New NASA popup created");
Self::new(RLColor::LIGHT_BLUE, text, 10)
}
pub fn mars(text: String) -> Self {
info!("New MARS popup created");
Self::new(RLColor::LIGHT_GREY, text, 10)
}
pub fn warning(text: String) -> Self {
info!("New WARNING popup created");
Self::new(RLColor::RED, text, 10)
}
pub(crate) fn new(color: Color, text: String, duration: u64) -> Self {
info!("New popup created: text: {}, duration: {}", text, duration);
Self {
color,
text,
Expand Down Expand Up @@ -151,6 +156,7 @@ impl event::EventHandler<RLError> for Screenstack {

impl Default for Screenstack {
fn default() -> Self {
info!("Default Screenstack created");
let (sender, receiver) = channel();
Self {
screens: vec![Box::new(MainMenu::new(sender.clone()))],
Expand Down
6 changes: 6 additions & 0 deletions game/src/game_core/deathscreen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use ggez::winit::event::VirtualKeyCode;
use ggez::{graphics, Context};
use std::fmt::{Debug, Display, Formatter};
use std::sync::mpsc::Sender;
use tracing::info;

/// Create DeathScreen using deathscreen::new() and pass reason of death from DeathReason enum.
/// # Example
Expand Down Expand Up @@ -38,6 +39,7 @@ pub struct DeathScreen {

impl DeathScreen {
pub fn new(death_reason: DeathReason, sender: Sender<StackCommand>) -> Self {
info!("The player died due to a lack of : {:?}", death_reason);
Self {
buttons: vec![],
death_reason,
Expand All @@ -52,6 +54,10 @@ impl Screen for DeathScreen {
fn update(&mut self, ctx: &mut Context) -> RLResult {
let keys = ctx.keyboard.pressed_keys();
if let Some(key) = keys.iter().next() {
info!(
"The player wants to return to the main menu with: {:?}",
key
);
match key {
VirtualKeyCode::Escape => self.sender.send(StackCommand::Push(Box::new(
MainMenu::new(self.sender.clone()),
Expand Down
9 changes: 8 additions & 1 deletion game/src/game_core/event.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use tracing::info;

pub const KOMETENEINSCHLAG: [&str; 2] = [
"KOMETENEINSCHLAG",
Expand Down Expand Up @@ -27,6 +28,11 @@ pub(crate) struct Event {
}
impl Event {
pub fn new(event: [&str; 2]) -> Self {
info!(
"New event created: {}, info text: {}",
event[0].to_string(),
event[1].to_string()
);
Self {
name: event[0].to_string(),
info_text: event[1].to_string(),
Expand All @@ -47,7 +53,8 @@ impl Event {
}
}
pub fn restore_event() -> Option<Event> {
//Sender is missing -> Should send reverse of event cr
info!("Event X restored"); // Fill missing parameters
//Sender is missing -> Should send reverse of event cr
None
}
}
6 changes: 6 additions & 0 deletions game/src/game_core/item.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use serde::{Deserialize, Serialize};
use tracing::info;

pub const GEDRUCKTESTEIL: [&str; 3] = [
"3D-gedrucktes-Teil",
"Ein 3D-gedrucktes-Teil, welches zur Reparatur des Kommunikationsmoduls verwendet werden kann",
Expand All @@ -24,6 +26,10 @@ pub struct Item {
}
impl Item {
pub(crate) fn new(item: [&str; 3]) -> Self {
info!(
"New Item created: name: {}, info_text: {}, img path: {}",
item[0], item[1], item[2]
);
Self {
name: item[0].to_string(),
info_text: item[1].to_string(),
Expand Down
24 changes: 15 additions & 9 deletions game/src/game_core/player.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::backend::gamestate::GameState;
use crate::backend::popup_messages::{GAME_INFO, WARNINGS};
use crate::backend::popup_messages::GAME_INFO;
use crate::backend::rlcolor::RLColor;
use crate::backend::screen::{Popup, StackCommand};
use crate::game_core::item::{Item, BENZIN, GEDRUCKTESTEIL, SUPER_GLUE};
use crate::game_core::resources::Resources;

use serde::{Deserialize, Serialize};
use std::sync::mpsc::Sender;
use tracing::info;

/// The current game player, containing its inventory and the current position, air and energy,
/// along with their change rate
Expand All @@ -23,6 +24,7 @@ pub struct Player {
}
impl Default for Player {
fn default() -> Self {
info!("Default Player created");
Self {
inventory: vec![
(Item::new(SUPER_GLUE), 0),
Expand Down Expand Up @@ -58,6 +60,9 @@ impl Player {
) {
// If Player has full life and is healing, stop healing, reset last damage
(change_life, _, u16::MAX) if change_life >= 0 => {
if self.resources_change.life > 0 {
info!("Player has full life, stopping healing");
}
self.resources_change.life = 0;
self.last_damage = 0;
}
Expand All @@ -66,10 +71,11 @@ impl Player {
self.last_damage = 0;
}
// If player does not take damage and 5 seconds have passed, start healing
(0, last_damage, _) if last_damage >= 900 => {
(0, last_damage, _) if last_damage >= 600 => {
self.resources_change.life += 5;
self.last_damage = 0;
let popup = Popup::new(RLColor::GREEN, GAME_INFO[0].to_string(), 5);
info!("Player startet healing");
sender.send(StackCommand::Popup(popup)).unwrap();
}
// If player takes damage, increase last damage point
Expand All @@ -96,13 +102,13 @@ mod test {

fn setup_gamestate() -> (GameState, Receiver<StackCommand>) {
let mut gamestate = GameState::default();
let mut channel = channel();
let channel = channel();
gamestate.set_sender(channel.0);
(gamestate, channel.1)
}
#[test]
fn test_case_one_life_regeneration() {
let (mut gamestate, _) = setup_gamestate();
let (gamestate, _) = setup_gamestate();
let mut player = Player::default();
player.resources.life = u16::MAX;
player.resources_change.life = 5;
Expand All @@ -114,7 +120,7 @@ mod test {

#[test]
fn test_case_two_life_regeneration() {
let (mut gamestate, _) = setup_gamestate();
let (gamestate, _) = setup_gamestate();
let mut player = Player::default();
player.resources.life = 1000;
player.resources_change.life = 5;
Expand All @@ -125,7 +131,7 @@ mod test {

#[test]
fn test_case_three_life_regeneration() {
let (mut gamestate, _receiver) = setup_gamestate();
let (gamestate, _receiver) = setup_gamestate();
let mut player = Player::default();
player.resources.life = 1000;
player.resources_change.life = 0;
Expand All @@ -137,7 +143,7 @@ mod test {

#[test]
fn test_case_four_life_regeneration() {
let (mut gamestate, _) = setup_gamestate();
let (gamestate, _) = setup_gamestate();
let mut player = Player::default();
player.resources.life = 20000;
player.last_damage = 400;
Expand All @@ -150,7 +156,7 @@ mod test {
#[test]
fn test_case_five_life_regeneration() {
let (mut gamestate, _) = setup_gamestate();
let mut channel = channel();
let channel = channel();
gamestate.set_sender(channel.0);
let mut player = Player::default();
player.last_damage = 3;
Expand Down
Loading

0 comments on commit b5aa197

Please sign in to comment.