learning-rust/src/rpg.rs
2023-11-15 15:04:35 +01:00

151 lines
3.6 KiB
Rust

use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
enum Class {
Paladin,
Mage { mana: i64 },
Thief,
}
impl std::fmt::Display for Class {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
Class::Paladin => {
write!(f, "Paladin")
}
Class::Mage { mana } => {
write!(f, "Mage(mana={})", mana)
}
Class::Thief => {
write!(f, "Thief")
}
}
}
}
#[derive(Debug, Clone, Eq)]
struct Character {
name: String,
hp: u64,
class: Class,
}
impl std::fmt::Display for Character {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{}: {} with {} hp", self.name, self.class, self.hp)
}
}
impl std::cmp::PartialEq for Character {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.class == other.class
}
}
impl std::cmp::Ord for Character {
fn cmp(&self, other: &Character) -> std::cmp::Ordering {
self.name.cmp(&other.name)
}
}
impl std::cmp::PartialOrd for Character {
fn partial_cmp(&self, other: &Character) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Character {
fn new(name: &str) -> Self {
Self {
name: name.to_owned(),
hp: 100,
class: Class::Paladin,
}
}
fn heal(&mut self, hp: u64) {
//print!("Before healing:");
//self.print();
self.hp = (self.hp + hp).min(100);
//print!("After healing:");
//self.print();
}
fn paladin(name: &str) -> Self {
Character::new(name)
}
fn thief(name: &str) -> Self {
let mut character = Self::new(name);
character.class = Class::Thief;
character
}
fn mage(name: &str) -> Self {
let mut character = Self::new(name);
character.class = Class::Mage { mana: 100 };
character
}
fn _print(&self) {
match self.class {
Class::Paladin => {
println!("Paladin {} ({} hp)", self.name, self.hp);
}
Class::Mage { mana } => {
println!("Mage ({}) {} ({} hp)", mana, self.name, self.hp);
}
Class::Thief => {
println!("Thief {} ({} hp)", self.name, self.hp);
}
}
}
fn cast_spell(&mut self, other: &mut Character) {
if let Class::Mage { mana } = self.class {
if mana > 25 {
//println!("{} casting a spell to {}", self.name, other.name);
other.hp = (other.hp - 25).max(0);
self.class = Class::Mage { mana: mana - 25 };
} else {
//println!("Has not enoug mana!");
}
other.hp -= 50;
} else {
//println!("{} cannot cast spell!", self.name);
self.hp = (self.hp - 5).max(0);
}
}
}
// impl Class {
// fn mana(&self) -> Option<&i64> {
// match self {
// Self::Mage { mana } => Some(mana),
// _ => None,
// }
// }
// }
fn test_rpg() {
let mut ada = Character::mage("Ada");
let mut alan = Character::paladin("Alan");
let mut windark = Character::thief("Windark");
ada.heal(0);
ada.cast_spell(&mut alan);
alan.cast_spell(&mut ada);
ada.cast_spell(&mut windark);
windark.cast_spell(&mut ada);
//println!("{}", ada);
//println!("{}", alan);
//println!("{}", windark);
//dbg!(ada);
}
pub fn main() {
test_rpg();
}