use super::{remove_leading_newlines, Sprite, TextAlign2D};
use crate::elements::{
view::{Modifier, ViewElement},
Pixel, Vec2D,
};
pub struct AnimatedSprite {
pub pos: Vec2D,
pub frames: Vec<String>,
pub current_frame: usize,
pub modifier: Modifier,
pub align: TextAlign2D,
}
impl AnimatedSprite {
#[must_use]
pub fn new(pos: Vec2D, frames: &[&str], modifier: Modifier) -> Self {
let processed_frames: Vec<String> = frames
.iter()
.map(|frame| remove_leading_newlines(frame))
.collect();
Self {
pos,
frames: processed_frames,
current_frame: 0,
modifier,
align: TextAlign2D::default(),
}
}
pub fn next_frame(&mut self) {
self.current_frame += 1;
self.current_frame %= self.frames.len();
}
#[must_use]
pub fn is_within_frame_range(&self) -> bool {
self.current_frame < self.frames.len()
}
}
impl ViewElement for AnimatedSprite {
fn active_pixels(&self) -> Vec<Pixel> {
assert!(
self.is_within_frame_range(),
"AnimatedSprite tried indexing at {} in list of frames size {}",
self.current_frame,
self.frames.len()
);
Sprite::draw(self.pos, &self.frames[self.current_frame], self.modifier)
}
}