Compare commits
1 Commits
add_messag
...
make_monst
| Author | SHA1 | Date | |
|---|---|---|---|
| cca9e8f285 |
7
build.rs
7
build.rs
@@ -1,7 +0,0 @@
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
let output = Command::new("git").args(&["rev-parse", "--short", "HEAD"]).output().unwrap();
|
||||
let git_hash = String::from_utf8(output.stdout).unwrap();
|
||||
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ pub trait Artifact {
|
||||
/// get the position of the artifact in the level
|
||||
fn get_immutable_position(&self) -> &Position;
|
||||
/// call to apply the effects of the artifact to the player
|
||||
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>);
|
||||
fn collect(&mut self, player: &mut Player);
|
||||
/// returns if the artifact was collected and can be removed from the level
|
||||
fn was_collected(&self) -> bool;
|
||||
}
|
||||
@@ -37,9 +37,8 @@ impl Artifact for Chest {
|
||||
}
|
||||
|
||||
fn get_immutable_position(&self) -> &Position { &self.position }
|
||||
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>) {
|
||||
fn collect(&mut self, player: &mut Player) {
|
||||
player.retrieve_gold(self.gold);
|
||||
messages.insert(0, format!("opened chest and collected {} gold.", self.gold).to_string());
|
||||
self.gold = 0;
|
||||
}
|
||||
|
||||
@@ -68,17 +67,9 @@ impl Artifact for Potion {
|
||||
("P", Color::Green)
|
||||
}
|
||||
fn get_immutable_position(&self) -> &Position { &self.position }
|
||||
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>) {
|
||||
// only consume potion of the player can gain at least one health point
|
||||
if !player.is_healthy() {
|
||||
let old = player.get_life();
|
||||
fn collect(&mut self, player: &mut Player) {
|
||||
player.change_life(self.health.try_into().unwrap());
|
||||
let new = player.get_life();
|
||||
messages.insert(0, format!("picked up potion and gained {} hp.", new - old).to_string());
|
||||
self.health = 0;
|
||||
} else {
|
||||
messages.insert(0, "not using the potion because you're healthy.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn was_collected(&self) -> bool {
|
||||
|
||||
31
src/game.rs
31
src/game.rs
@@ -1,7 +1,7 @@
|
||||
use crate::level::{Level, StructureElement};
|
||||
use crate::level_generator::LevelGenerator;
|
||||
use crate::player::Player;
|
||||
use crate::position::{HasPosition, Position};
|
||||
use crate::position::Position;
|
||||
|
||||
pub const LEVELS: usize = 10;
|
||||
|
||||
@@ -23,7 +23,6 @@ pub struct Game {
|
||||
player: Player,
|
||||
/// the levels of the game
|
||||
levels: Vec<Level>,
|
||||
pub messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Game {
|
||||
@@ -35,7 +34,6 @@ impl Game {
|
||||
let mut g = Game {
|
||||
player: p,
|
||||
levels: v,
|
||||
messages: Vec::with_capacity(10),
|
||||
};
|
||||
let start = {
|
||||
g.get_level(0).start
|
||||
@@ -45,6 +43,8 @@ impl Game {
|
||||
g
|
||||
}
|
||||
|
||||
/// returns true if the player is dead (life <= 0)
|
||||
fn player_is_dead(&self) -> bool { self.get_player().get_life() <= 0 }
|
||||
/// returns true if the player is standing on the End element
|
||||
fn player_reached_goal(&mut self) -> bool {
|
||||
match self.next_element(0, 0) {
|
||||
@@ -60,7 +60,7 @@ impl Game {
|
||||
}
|
||||
/// returns the state of the game (depending on player's life and position)
|
||||
pub fn get_game_state(&mut self) -> GameState {
|
||||
if self.player.is_dead() {
|
||||
if self.player_is_dead() {
|
||||
return GameState::LOST;
|
||||
}
|
||||
if self.player_reached_goal() {
|
||||
@@ -80,8 +80,19 @@ impl Game {
|
||||
/// limitation as walls.
|
||||
fn can_move(&mut self, dx: i16, dy: i16) -> bool {
|
||||
let player_pos = &self.player.get_position();
|
||||
let new_x: i16 = player_pos.get_x() as i16 + dx;
|
||||
let new_y: i16 = player_pos.get_y() as i16 + dy;
|
||||
let level = &mut self.levels[player_pos.get_level()];
|
||||
level.can_player_move(&self.player, dx, dy)
|
||||
match level.get_element(new_x, new_y) {
|
||||
(None, _, _) => { return false; }
|
||||
(Some(t), _, _) => {
|
||||
match t {
|
||||
StructureElement::Wall => { return false; }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
true
|
||||
}
|
||||
/// returns the position (as tuple) of the next level's start point.
|
||||
fn next_start(&self) -> (usize, usize, usize) {
|
||||
@@ -127,14 +138,12 @@ impl Game {
|
||||
(dx, dy) = (0, 0);
|
||||
let (next_level, x, y) = self.next_start();
|
||||
player_level = next_level;
|
||||
self.messages.insert(0, format!("you climb down to level {}.", next_level));
|
||||
self.get_mutable_player().get_position().set(next_level, x, y);
|
||||
}
|
||||
StructureElement::StairUp => {
|
||||
(dx, dy) = (0, 0);
|
||||
let (next_level, x, y) = self.prev_end();
|
||||
player_level = next_level;
|
||||
self.messages.insert(0, format!("you climb up to level {}.", next_level));
|
||||
self.get_mutable_player().get_position().set(next_level, x, y);
|
||||
}
|
||||
_ => {}
|
||||
@@ -159,8 +168,6 @@ impl Game {
|
||||
// TODO fight the monster
|
||||
self.player.change_life(-1);
|
||||
m.decrease_life(1);
|
||||
self.messages.insert(0, format!("{} hits you.", m.get_name()).to_string());
|
||||
self.messages.insert(0, format!("you hit {}.", m.get_name()).to_string());
|
||||
// monster died, player gains experience
|
||||
if m.is_dead() {
|
||||
self.player.gain_experience(m.get_experience_gain());
|
||||
@@ -178,16 +185,16 @@ impl Game {
|
||||
match a {
|
||||
None => {}
|
||||
Some(a) => {
|
||||
a.collect(&mut self.player, &mut self.messages);
|
||||
a.collect(&mut self.player);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// updates the player's current level. This will remove collected artifacts and dead monsters.
|
||||
pub fn update_level(&mut self, ticks: u128) {
|
||||
pub fn update_level(&mut self, ticks: u64) {
|
||||
let player_pos = &self.player.get_immutable_position();
|
||||
let player_level = player_pos.get_level();
|
||||
let level = &mut self.levels[player_level];
|
||||
level.update(ticks, &mut self.player, &mut self.messages);
|
||||
level.update(ticks);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
183
src/level.rs
183
src/level.rs
@@ -1,16 +1,11 @@
|
||||
use std::cmp::{max, min};
|
||||
|
||||
use rand::Rng;
|
||||
use rand::rngs::ThreadRng;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::artifacts::{Chest, Potion};
|
||||
use crate::artifacts::Artifact;
|
||||
#[cfg(test)]
|
||||
use crate::monster::{Orc, Rat};
|
||||
use crate::monster::Monster;
|
||||
use crate::player::Player;
|
||||
use crate::position::HasPosition;
|
||||
#[cfg(test)]
|
||||
use crate::monster::Rat;
|
||||
use crate::position::Position;
|
||||
|
||||
pub const LEVEL_WIDTH: usize = 50;
|
||||
@@ -37,10 +32,27 @@ pub struct Level {
|
||||
pub(crate) start: (usize, usize),
|
||||
/// the position of the end in the level (either stair down or end point)
|
||||
pub(crate) end: (usize, usize),
|
||||
pub(crate) rng: ThreadRng,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
#[cfg(test)]
|
||||
pub fn new(level: usize) -> Level {
|
||||
let mut s = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
|
||||
for x in 2..LEVEL_WIDTH - 2 {
|
||||
for y in 2..LEVEL_HEIGHT - 2 {
|
||||
s[x][y] = StructureElement::Floor;
|
||||
}
|
||||
}
|
||||
Level {
|
||||
level,
|
||||
structure: s,
|
||||
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
|
||||
monsters: Vec::with_capacity(10),
|
||||
artifacts: Vec::with_capacity(10),
|
||||
start: (0, 0),
|
||||
end: (0, 0),
|
||||
}
|
||||
}
|
||||
pub fn get_element(&mut self, x: i16, y: i16) -> (Option<StructureElement>, Option<&mut Box<(dyn Monster + 'static)>>, Option<&mut Box<(dyn Artifact + 'static)>>) {
|
||||
if x < 0 || y < 0 {
|
||||
return (None, None, None);
|
||||
@@ -68,6 +80,33 @@ impl Level {
|
||||
}
|
||||
(Some(self.structure[x][y]), res_m, res_a)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn add_monster(&mut self, mut monster: impl Monster + 'static) -> Result<(), String> {
|
||||
if self.level != monster.get_position().get_level() {
|
||||
return Err("Wrong Level".to_string());
|
||||
}
|
||||
for m in &mut self.monsters {
|
||||
if m.get_position() == monster.get_position() {
|
||||
return Err("Position already used".to_string());
|
||||
}
|
||||
}
|
||||
self.monsters.push(Box::new(monster));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn add_artifact(&mut self, artifact: impl Artifact + 'static) -> Result<(), String> {
|
||||
if self.level != artifact.get_immutable_position().get_level() {
|
||||
return Err("Wrong Level".to_string());
|
||||
}
|
||||
for a in &mut self.artifacts {
|
||||
if a.get_immutable_position() == artifact.get_immutable_position() {
|
||||
return Err("Position already used".to_string());
|
||||
}
|
||||
}
|
||||
self.artifacts.push(Box::new(artifact));
|
||||
Ok(())
|
||||
}
|
||||
/// discover the area with in the level around the given position
|
||||
pub fn discover(&mut self, pos: &Position) {
|
||||
let x = pos.get_x();
|
||||
@@ -112,118 +151,29 @@ impl Level {
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn update(&mut self, ticks: u128, player: &mut Player, messages: &mut Vec<String>) {
|
||||
|
||||
pub fn update(&mut self, ticks: u64) {
|
||||
for (index, a) in &mut self.artifacts.iter().enumerate() {
|
||||
if a.was_collected() {
|
||||
self.artifacts.remove(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for index in 0..self.monsters.len() {
|
||||
if self.monsters[index].is_dead() {
|
||||
continue;
|
||||
}
|
||||
if ticks % self.monsters[index].get_ticks_between_steps() != 0 {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
// calculate the direction the monster will try to walk
|
||||
let (dx, dy) = match self.rng.gen_range(0..5) {
|
||||
1 => { (1, 0) }
|
||||
2 => { (-1, 0) }
|
||||
3 => { (0, 1) }
|
||||
4 => { (0, -1) }
|
||||
_ => { (0, 0) }
|
||||
};
|
||||
if self.can_monster_move(self.monsters[index].as_ref(), dx, dy) {
|
||||
let (new_x, new_y) = self.monsters[index].get_position().change(dx, dy);
|
||||
if player.get_immutable_position().get_x() == new_x && player.get_immutable_position().get_y() == new_y {
|
||||
self.monsters[index].decrease_life(1);
|
||||
player.change_life(-1);
|
||||
messages.insert(0, format!("{} hits you.", self.monsters[index].get_name()).to_string());
|
||||
messages.insert(0, format!("you hit {}.", self.monsters[index].get_name()).to_string());
|
||||
// if the attack did not kill the opponent, back down
|
||||
if !player.is_dead() {
|
||||
self.monsters[index].get_position().change(-dx, -dy);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, m) in &mut self.monsters.iter().enumerate() {
|
||||
if m.is_dead() {
|
||||
self.monsters.remove(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_monster_move(&self, agent: &dyn Monster, dx: i16, dy: i16) -> bool {
|
||||
let agent_pos = agent.get_immutable_position();
|
||||
let new_x: usize = (agent_pos.get_x() as i16 + dx) as usize;
|
||||
let new_y: usize = (agent_pos.get_y() as i16 + dy) as usize;
|
||||
|
||||
if new_x >= LEVEL_WIDTH || new_y >= LEVEL_HEIGHT {
|
||||
return false;
|
||||
}
|
||||
|
||||
for index in 0..self.monsters.len() {
|
||||
let pos = self.monsters[index].get_immutable_position();
|
||||
if pos.get_x() == new_x && pos.get_y() == new_y { return false; }
|
||||
let mut dx = 0;
|
||||
let speed = 50;
|
||||
if ticks % speed == 0 {
|
||||
dx = if (ticks / speed) % 2 == 0 { -1 } else { 1 };
|
||||
}
|
||||
self.structure[new_x][new_y] != StructureElement::Wall
|
||||
|
||||
self.monsters[index].get_position().change(dx, 0);
|
||||
}
|
||||
pub fn can_player_move(&self, agent: &Player, dx: i16, dy: i16) -> bool {
|
||||
let agent_pos = agent.get_immutable_position();
|
||||
let new_x: usize = (agent_pos.get_x() as i16 + dx) as usize;
|
||||
let new_y: usize = (agent_pos.get_y() as i16 + dy) as usize;
|
||||
self.structure[new_x][new_y] != StructureElement::Wall
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn new(level: usize) -> Level {
|
||||
let mut s = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
|
||||
for x in 2..LEVEL_WIDTH - 2 {
|
||||
for y in 2..LEVEL_HEIGHT - 2 {
|
||||
s[x][y] = StructureElement::Floor;
|
||||
}
|
||||
}
|
||||
Level {
|
||||
level,
|
||||
structure: s,
|
||||
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
|
||||
monsters: Vec::with_capacity(10),
|
||||
artifacts: Vec::with_capacity(10),
|
||||
start: (0, 0),
|
||||
end: (0, 0),
|
||||
rng: rand::thread_rng(),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn add_monster(&mut self, mut monster: impl Monster + 'static) -> Result<(), String> {
|
||||
if self.level != monster.get_position().get_level() {
|
||||
return Err("Wrong Level".to_string());
|
||||
}
|
||||
for m in &mut self.monsters {
|
||||
if m.get_position() == monster.get_position() {
|
||||
return Err("Position already used".to_string());
|
||||
}
|
||||
}
|
||||
self.monsters.push(Box::new(monster));
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn add_artifact(&mut self, artifact: impl Artifact + 'static) -> Result<(), String> {
|
||||
if self.level != artifact.get_immutable_position().get_level() {
|
||||
return Err("Wrong Level".to_string());
|
||||
}
|
||||
for a in &mut self.artifacts {
|
||||
if a.get_immutable_position() == artifact.get_immutable_position() {
|
||||
return Err("Position already used".to_string());
|
||||
}
|
||||
}
|
||||
self.artifacts.push(Box::new(artifact));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,17 +202,20 @@ fn test_discover_get_element() {
|
||||
#[test]
|
||||
fn test_discover_can_add_monster() {
|
||||
let mut l = Level::new(0);
|
||||
let m = Rat::new_with_position(Position::new(1, 2, 3));
|
||||
let mut m = Rat::new(2);
|
||||
m.get_position().set(1, 2, 3);
|
||||
assert_eq!(l.add_monster(m), Err("Wrong Level".to_string()));
|
||||
|
||||
let mut m = Orc::new_with_position(Position::new(0, 2, 3));
|
||||
let mut m = Rat::new(2);
|
||||
m.get_position().set(0, 2, 3);
|
||||
assert_eq!(l.add_monster(m), Ok(()));
|
||||
|
||||
let m = Rat::new_with_position(Position::new(0, 2, 3));
|
||||
let mut m = Rat::new(2);
|
||||
m.get_position().set(0, 2, 3);
|
||||
assert_eq!(l.add_monster(m), Err("Position already used".to_string()));
|
||||
|
||||
let m = Rat::new_with_position(Position::new(0, 2, 4));
|
||||
let mut m = Rat::new(2);
|
||||
m.get_position().set(0, 2, 4);
|
||||
assert_eq!(l.add_monster(m), Ok(()));
|
||||
}
|
||||
|
||||
@@ -290,17 +243,18 @@ fn test_discover_get_monster() {
|
||||
assert_eq!(l.get_element(10, 10).0.unwrap(), StructureElement::Floor);
|
||||
assert!(l.get_element(10, 10).1.is_none());
|
||||
|
||||
let m = Rat::new_with_position(Position::new(0, 10, 10));
|
||||
let mut m = Rat::new(23);
|
||||
m.get_position().set(0, 10, 10);
|
||||
assert_eq!(l.add_monster(m), Ok(()));
|
||||
|
||||
let elem = l.get_element(10, 10);
|
||||
assert_eq!(elem.0.unwrap(), StructureElement::Floor);
|
||||
assert!(elem.1.is_some());
|
||||
let m = elem.1.unwrap();
|
||||
assert_eq!(m.get_life(), 2);
|
||||
assert_eq!(m.get_life(), 23);
|
||||
|
||||
m.decrease_life(2);
|
||||
assert_eq!(l.get_element(10, 10).1.unwrap().get_life(), 0);
|
||||
assert_eq!(l.get_element(10, 10).1.unwrap().get_life(), 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -325,7 +279,8 @@ fn test_discover_get_monster_can_move() {
|
||||
let p = Position::new(0, 10, 10);
|
||||
l.discover(&p);
|
||||
|
||||
let m = Rat::new_with_position(Position::new(0, 10, 10));
|
||||
let mut m = Rat::new(23);
|
||||
m.get_position().set(0, 10, 10);
|
||||
l.add_monster(m).expect("Panic because of");
|
||||
|
||||
let m = l.get_element(10, 10).1.unwrap();
|
||||
@@ -335,5 +290,5 @@ fn test_discover_get_monster_can_move() {
|
||||
assert!(m.is_none());
|
||||
let m = l.get_element(11, 11).1;
|
||||
assert!(m.is_some());
|
||||
assert_eq!(m.unwrap().get_life(), 2);
|
||||
assert_eq!(m.unwrap().get_life(), 23);
|
||||
}
|
||||
|
||||
@@ -344,7 +344,6 @@ impl LevelGenerator {
|
||||
artifacts,
|
||||
start: (start_x, start_y),
|
||||
end: (end_x, end_y),
|
||||
rng: rand::thread_rng(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ use ratatui::widgets::{StatefulWidget, Widget};
|
||||
|
||||
use crate::game::Game;
|
||||
use crate::level::StructureElement;
|
||||
use crate::position::HasPosition;
|
||||
|
||||
const FG_BROWN: Color = Color::Rgb(186, 74, 0);
|
||||
|
||||
|
||||
85
src/main.rs
85
src/main.rs
@@ -1,6 +1,5 @@
|
||||
use std::io::Result;
|
||||
use std::io::stdout;
|
||||
use std::time::Instant;
|
||||
|
||||
use crossterm::{
|
||||
event::{self, KeyCode, KeyEventKind},
|
||||
@@ -8,7 +7,7 @@ use crossterm::{
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
};
|
||||
use ratatui::{
|
||||
prelude::{CrosstermBackend, Terminal},
|
||||
prelude::{CrosstermBackend, Stylize, Terminal},
|
||||
widgets::Paragraph,
|
||||
};
|
||||
use ratatui::prelude::*;
|
||||
@@ -18,8 +17,8 @@ use whoami::realname;
|
||||
|
||||
use crate::game::{Game, GameState};
|
||||
use crate::level_widget::LevelWidget;
|
||||
// use crate::level_widget::LevelWidget;
|
||||
use crate::player::Player;
|
||||
use crate::position::HasPosition;
|
||||
|
||||
mod game;
|
||||
mod player;
|
||||
@@ -30,9 +29,6 @@ mod level_generator;
|
||||
mod artifacts;
|
||||
mod monster;
|
||||
|
||||
/// length of a game frame in ms
|
||||
pub const FRAME_LENGTH: u64 = 100;
|
||||
|
||||
//
|
||||
fn main() -> Result<()> {
|
||||
let mut game = Game::new(Player::new(realname().as_str(), 10));
|
||||
@@ -42,29 +38,12 @@ fn main() -> Result<()> {
|
||||
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
terminal.clear()?;
|
||||
|
||||
let start_time = Instant::now();
|
||||
let mut ticks = 0;
|
||||
let mut ticks: u64 = 0;
|
||||
loop {
|
||||
terminal.draw(|frame| {
|
||||
let mut area = frame.size();
|
||||
frame.render_widget(Block::default().style(Style::default().bg(Color::Green)), area);
|
||||
|
||||
// don't draw stuff except an info box if the terminal is too small (less than 80x25)
|
||||
// to prevent the read drawing code from crashing the game.
|
||||
if area.width < 80 || area.height < 25 {
|
||||
let block = Block::default()
|
||||
.title("Info")
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Color::White))
|
||||
.border_type(BorderType::Rounded)
|
||||
.style(Style::default().bg(Color::Black));
|
||||
let paragraph = Paragraph::new("Terminal needs to be at leas 80x25!")
|
||||
.block(block)
|
||||
.wrap(Wrap { trim: true });
|
||||
frame.render_widget(paragraph, area);
|
||||
return;
|
||||
}
|
||||
|
||||
if area.width > 80 {
|
||||
area.x = (area.width - 80) / 2;
|
||||
area.width = 80;
|
||||
@@ -86,54 +65,25 @@ fn main() -> Result<()> {
|
||||
x: area.x + 50,
|
||||
y: area.y,
|
||||
width: 30,
|
||||
height: 15,
|
||||
height: 25,
|
||||
};
|
||||
let block = Block::default()
|
||||
.title(
|
||||
Title::from(
|
||||
format!(" {} ", game.get_player().get_name()))
|
||||
.alignment(Alignment::Center)
|
||||
.position(Position::Top)
|
||||
)
|
||||
.borders(Borders::TOP)
|
||||
.border_style(Style::default().fg(Color::White))
|
||||
.border_type(BorderType::Rounded)
|
||||
.style(Style::default().bg(Color::Blue));
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!("Health: {}/{}\nExp: {}\nGold: {}\nLevel: {}",
|
||||
Paragraph::new(format!("{}\nHealth: {}/{}\nExp: {}\nGold: {}\nLevel: {}\nticks: {}",
|
||||
game.get_player().get_name(),
|
||||
game.get_player().get_life(),
|
||||
game.get_player().get_max_life(),
|
||||
game.get_player().get_experience(),
|
||||
game.get_player().get_gold(),
|
||||
game.get_player().get_immutable_position().get_level()))
|
||||
.block(block).wrap(Wrap { trim: true }),
|
||||
game.get_player().get_immutable_position().get_level(),
|
||||
ticks
|
||||
))
|
||||
.white()
|
||||
.on_blue(),
|
||||
stats_area,
|
||||
);
|
||||
let messages_area = Rect {
|
||||
x: area.x + 50,
|
||||
y: area.y + 15,
|
||||
width: 30,
|
||||
height: 10,
|
||||
};
|
||||
// Display the latest messages from the game to the user
|
||||
let block = Block::default()
|
||||
.title(Title::from(" messages ").alignment(Alignment::Center).position(Position::Top))
|
||||
.borders(Borders::TOP)
|
||||
.border_style(Style::default().fg(Color::White))
|
||||
.border_type(BorderType::Rounded)
|
||||
.style(Style::default().bg(Color::Blue));
|
||||
|
||||
let paragraph1 = if game.messages.is_empty() { "".to_string() } else { format!("> {}", game.messages.join("\n> ")) };
|
||||
frame.render_widget(
|
||||
Paragraph::new(paragraph1).block(block).wrap(Wrap { trim: true }),
|
||||
messages_area,
|
||||
);
|
||||
})?;
|
||||
if event::poll(std::time::Duration::from_millis(FRAME_LENGTH))? {
|
||||
if event::poll(std::time::Duration::from_millis(50))? {
|
||||
if let event::Event::Key(key) = event::read()? {
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('v') {
|
||||
game.messages.insert(0, format!("You are playing version '{}'.", env!("GIT_HASH")).to_string());
|
||||
}
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
|
||||
break;
|
||||
}
|
||||
@@ -150,16 +100,15 @@ fn main() -> Result<()> {
|
||||
game.move_player(new_pos.0, new_pos.1);
|
||||
}
|
||||
game.player_collects_artifact();
|
||||
if game.get_game_state() != GameState::RUNNING {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
game.update_level(ticks);
|
||||
if game.get_game_state() != GameState::RUNNING {
|
||||
break;
|
||||
}
|
||||
ticks+=1;
|
||||
}
|
||||
let playtime = start_time.elapsed();
|
||||
loop {
|
||||
let _ = terminal.draw(|frame| {
|
||||
let mut area = frame.size();
|
||||
@@ -170,7 +119,7 @@ fn main() -> Result<()> {
|
||||
area.width = 40;
|
||||
area.height = 20;
|
||||
let block = Block::default()
|
||||
.title(Title::from(" Game ended ").alignment(Alignment::Center).position(Position::Top))
|
||||
.title("Game ended")
|
||||
.title(Title::from("Press `q` to quit!").position(Position::Bottom))
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Color::White))
|
||||
@@ -189,7 +138,6 @@ fn main() -> Result<()> {
|
||||
};
|
||||
text += format!("\nYou gained {} experience.", game.get_player().get_experience()).as_str();
|
||||
text += format!("\nYou collected {} gold.", game.get_player().get_gold()).as_str();
|
||||
text += format!("\nYou played {} seconds.", playtime.as_secs()).as_str();
|
||||
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });
|
||||
frame.render_widget(paragraph, area);
|
||||
});
|
||||
@@ -201,6 +149,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
disable_raw_mode()?;
|
||||
Ok(())
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
use ratatui::prelude::Color;
|
||||
|
||||
use crate::position::{HasPosition, Position};
|
||||
use crate::position::Position;
|
||||
|
||||
pub trait Monster: HasPosition {
|
||||
fn get_name(&self) -> &str;
|
||||
pub trait Monster {
|
||||
fn is_dead(&self) -> bool;
|
||||
fn get_representation(&self) -> (&str, Color);
|
||||
fn decrease_life(&mut self, by: usize);
|
||||
// fn get_immutable_position(&self) -> &Position;
|
||||
fn get_immutable_position(&self) -> &Position;
|
||||
fn get_experience_gain(&self) -> usize;
|
||||
fn get_ticks_between_steps(&self) -> u128;
|
||||
fn get_position(&mut self) -> &mut Position;
|
||||
#[cfg(test)]
|
||||
fn get_life(&self) -> usize;
|
||||
}
|
||||
@@ -17,76 +16,87 @@ pub trait Monster: HasPosition {
|
||||
macro_rules! default_monster {
|
||||
($($t:ty),+ $(,)?) => ($(
|
||||
impl Monster for $t {
|
||||
fn get_name(&self) -> &str { &self.name }
|
||||
fn is_dead(&self) -> bool { self.life <= 0 }
|
||||
fn get_experience_gain(&self) -> usize { self.experience_gain }
|
||||
fn get_representation(&self) -> (&str, Color) { (&self.symbol, self.color) }
|
||||
fn decrease_life(&mut self, by: usize) {
|
||||
self.life = self.life.saturating_sub(by);
|
||||
}
|
||||
fn get_ticks_between_steps(&self) -> u128 { self.ticks_between_steps }
|
||||
|
||||
#[cfg(test)]
|
||||
fn get_life(&self) -> usize { self.life }
|
||||
}
|
||||
impl HasPosition for $t {
|
||||
fn get_position(&mut self) -> &mut Position {
|
||||
&mut self.position
|
||||
}
|
||||
fn get_immutable_position(&self) -> &Position {
|
||||
&self.position
|
||||
}
|
||||
fn get_position(&mut self) -> &mut Position {
|
||||
&mut self.position
|
||||
}
|
||||
#[cfg(test)]
|
||||
fn get_life(&self) -> usize { self.life }
|
||||
}
|
||||
)+)
|
||||
}
|
||||
|
||||
pub struct Rat {
|
||||
name: String,
|
||||
life: usize,
|
||||
position: Position,
|
||||
symbol: String,
|
||||
color: Color,
|
||||
experience_gain: usize,
|
||||
ticks_between_steps: u128,
|
||||
}
|
||||
|
||||
impl Rat {
|
||||
#[cfg(test)]
|
||||
pub fn new(life: usize) -> Self {
|
||||
Self {
|
||||
life,
|
||||
position: Position::new(0, 0, 0),
|
||||
symbol: String::from("R"),
|
||||
color: Color::Black,
|
||||
experience_gain: 5,
|
||||
}
|
||||
}
|
||||
pub fn new_with_position(position: Position) -> Self {
|
||||
Self {
|
||||
name: "rat".to_string(),
|
||||
life: 2,
|
||||
position,
|
||||
symbol: String::from("R"),
|
||||
color: Color::Black,
|
||||
experience_gain: 5,
|
||||
ticks_between_steps: 5,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn get_life(&self) -> usize { self.life }
|
||||
}
|
||||
default_monster!(Rat);
|
||||
|
||||
pub struct Orc {
|
||||
name: String,
|
||||
life: usize,
|
||||
position: Position,
|
||||
symbol: String,
|
||||
color: Color,
|
||||
experience_gain: usize,
|
||||
ticks_between_steps: u128,
|
||||
}
|
||||
|
||||
impl Orc {
|
||||
#[cfg(test)]
|
||||
pub fn new(life: usize) -> Self {
|
||||
Self {
|
||||
life,
|
||||
position: Position::new(0, 0, 0),
|
||||
symbol: String::from("O"),
|
||||
color: Color::DarkGray,
|
||||
experience_gain: 10,
|
||||
}
|
||||
}
|
||||
pub fn new_with_position(position: Position) -> Self {
|
||||
Self {
|
||||
name: "orc".to_string(),
|
||||
life: 4,
|
||||
position,
|
||||
symbol: String::from("O"),
|
||||
color: Color::DarkGray,
|
||||
experience_gain: 10,
|
||||
ticks_between_steps: 10,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn get_life(&self) -> usize { self.life }
|
||||
}
|
||||
|
||||
default_monster!(Orc);
|
||||
@@ -94,7 +104,7 @@ default_monster!(Orc);
|
||||
|
||||
#[test]
|
||||
fn monsters_can_move() {
|
||||
let mut m = Rat::new_with_position(Position::new(0, 0, 0));
|
||||
let mut m = Rat::new(2);
|
||||
assert_eq!(m.get_position(), &Position::new(0, 0, 0));
|
||||
m.get_position().change(1, 2);
|
||||
assert_eq!(m.get_position(), &Position::new(0, 1, 2));
|
||||
@@ -107,7 +117,7 @@ fn monsters_can_move() {
|
||||
|
||||
#[test]
|
||||
fn monsters_can_die() {
|
||||
let mut m = Rat::new_with_position(Position::new(0, 0, 0));
|
||||
let mut m = Rat::new(2);
|
||||
assert_eq!(m.get_life(), 2);
|
||||
assert_eq!(m.is_dead(), false);
|
||||
m.decrease_life(1);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::cmp::{max, min};
|
||||
|
||||
use crate::position::{HasPosition, Position};
|
||||
use crate::position::Position;
|
||||
|
||||
pub struct Player {
|
||||
name: String,
|
||||
@@ -31,13 +31,15 @@ impl Player {
|
||||
pub fn get_life(&self) -> i16 {
|
||||
self.life
|
||||
}
|
||||
/// returns true if the player is dead (life <= 0)
|
||||
pub fn is_dead(&self) -> bool { self.life <= 0 }
|
||||
/// returns true if the player's life is at maximum
|
||||
pub fn is_healthy(&self) -> bool { self.life == self.max_life }
|
||||
pub fn get_max_life(&self) -> i16 {
|
||||
self.max_life
|
||||
}
|
||||
pub fn get_position(&mut self) -> &mut Position {
|
||||
&mut self.position
|
||||
}
|
||||
pub fn get_immutable_position(&self) -> &Position {
|
||||
&self.position
|
||||
}
|
||||
|
||||
/// add the given amount to the players gold stash
|
||||
pub fn retrieve_gold(&mut self, amount: usize) { self.gold += amount }
|
||||
@@ -50,15 +52,6 @@ impl Player {
|
||||
pub fn get_experience(&self) -> usize { self.experience }
|
||||
}
|
||||
|
||||
impl HasPosition for Player {
|
||||
fn get_position(&mut self) -> &mut Position {
|
||||
&mut self.position
|
||||
}
|
||||
fn get_immutable_position(&self) -> &Position {
|
||||
&self.position
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_name() {
|
||||
let p = Player {
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
use std::cmp::max;
|
||||
|
||||
/// describes an character (PC or NPC) in the dungeon that has a position.
|
||||
pub trait HasPosition {
|
||||
/// returns a mutable position
|
||||
fn get_position(&mut self) -> &mut Position;
|
||||
/// returns an immutable position
|
||||
fn get_immutable_position(&self) -> &Position;
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub struct Position {
|
||||
level: usize,
|
||||
|
||||
Reference in New Issue
Block a user