babalcore 0.5.1

Babal core logic library, low-level things which are game-engine agnostic.
Documentation
use super::consts::*;
use super::slab::*;
use super::slab_def::*;

use super::slab_kind::*;

#[derive(Debug)]
pub struct Row {
    /// Slabs containing the actual data
    pub slabs: [Slab; WIDTH_MAX],
}

impl Row {
    /// Create a new row, with a given slab def.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let _row = Row::new(SlabDef::Floor);
    /// ```
    pub fn new(def: SlabDef) -> Row {
        Row {
            slabs: [Slab::new(def); WIDTH_MAX],
        }
    }

    /// Get a row content, at a given time.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let row = Row::new(SlabDef::Floor);
    /// assert_eq!(SlabKind::Floor, row.slab_kind(5, 123));
    /// ```
    pub fn slab_kind(&self, col: isize, now_msec: i64) -> SlabKind {
        if col < 0 || col >= WIDTH_MAX as isize {
            return SlabKind::Void;
        }
        self.slabs[col as usize].slab_kind(now_msec)
    }

    /// Set a row content.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let mut row = Row::default();
    /// assert_eq!(SlabKind::Void, row.slab_kind(3, 0));
    /// row.set(3, SlabDef::Floor);
    /// assert_eq!(SlabKind::Floor, row.slab_kind(3, 0));
    /// assert_eq!(SlabKind::Void, row.slab_kind(2, 0));
    /// ```
    pub fn set(&mut self, col: isize, def: SlabDef) {
        if col < 0 || col >= WIDTH_MAX as isize {
            return;
        }
        self.slabs[col as usize].set(def)
    }

    pub fn get(&self, col: isize) -> SlabDef {
        if col < 0 || col >= WIDTH_MAX as isize {
            SlabDef::Void
        } else {
            self.slabs[col as usize].get()
        }
    }
}

impl std::fmt::Display for Row {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str_list: Vec<String> = self
            .slabs
            .iter()
            .map(|x| format!("{}", x).to_string())
            .collect();
        write!(f, "{}", str_list.join(""))
    }
}

impl std::default::Default for Row {
    fn default() -> Self {
        Row {
            slabs: [Slab::new(SlabDef::Void); WIDTH_MAX],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fmt() {
        assert_eq!(
            "                                ",
            format!("{}", Row::new(SlabDef::Void))
        );
        assert_eq!(
            "################################",
            format!("{}", Row::new(SlabDef::Floor))
        );
    }
}