about summary refs log tree commit diff
path: root/src/entities/creature.rs
blob: 9fd8d23c752e9c1a499bdf6c9e03acf849f1dda4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crate::display;
use crate::entities::raws::CreatureType;
use crate::entities::raws::EntityRaw;
use crate::entities::{raw, EntityID};
use crate::types::Position;
use std::io::{self, Write};

#[derive(Debug, Clone)]
pub struct Creature {
    pub id: Option<EntityID>,
    pub typ: &'static CreatureType<'static>,
    pub position: Position,
    pub hitpoints: u16,
}

impl Creature {
    pub fn new_from_raw(name: &'static str, position: Position) -> Self {
        match raw(name) {
            EntityRaw::Creature(typ) => Self::new_with_type(typ, position),
            _ => panic!("Invalid raw type for {:?}, expected Creature", name),
        }
    }

    pub fn new_with_type(
        typ: &'static CreatureType<'static>,
        position: Position,
    ) -> Self {
        Creature {
            id: None,
            typ,
            position,
            hitpoints: typ.max_hitpoints,
        }
    }

    /// Damage the given creature by the given amount
    pub fn damage(&mut self, amount: u16) {
        if self.hitpoints <= amount {
            self.hitpoints = 0;
        } else {
            self.hitpoints -= amount;
        }
    }

    /// Returns true if this creature has died
    pub fn dead(&self) -> bool {
        self.hitpoints <= 0
    }
}

entity!(Creature);

impl display::Draw for Creature {
    fn do_draw(&self, out: &mut Write) -> io::Result<()> {
        write!(out, "{}", self.typ.chr)
    }
}