tavern_keeper/src/state.rs

164 lines
4.2 KiB
Rust

use std::rc::Rc;
use rand::prelude::*;
use crate::person::Person;
use crate::time::Time;
use crate::world::{World, Terrain, Town, Tavern, Structure};
use crate::events::{FoundTown, WorldGenesis, PersonGenesis, TavernBuilt};
pub struct GameState {
pub time: Time,
pub world: World,
pub people: Vec<Rc<Person>>,
pub events: Vec<Box<Event>>,
pub tavern: Option<Rc<Tavern>>,
}
pub struct Event {
pub time: Time,
pub effect: Box<dyn Effect>,
}
pub trait Effect {
fn apply(&self, state: &mut GameState);
fn description(&self) -> String;
}
impl Event {
pub fn description(&self) -> String {
format!("{}: {}", self.time, self.effect.description())
}
}
impl GameState {
pub fn new(world: World) -> GameState {
let mut events = Vec::new();
events.push(Box::new(Event {
time: Time { time: 0 },
effect: Box::new(WorldGenesis),
}));
GameState {
time: Time { time: 0 },
people: Vec::new(),
world: world,
events: events,
tavern: None,
}
}
pub fn set_tavern(&mut self, tavern: Rc<Tavern>) {
self.tavern = Some(tavern);
}
pub fn add_event(&mut self, event: Event) {
event.effect.apply(self);
self.events.push(Box::new(event));
}
pub fn step(&mut self) {
// for p in self.people.iter() {
// p.step(self);
// }
self.time.time += 1;
}
pub fn step_n(&mut self, n: u32) {
for _ in 0..n {
self.step();
}
}
pub fn step_year(&mut self) {
for _ in 0..360 {
self.step();
}
}
/**
* Getters
*/
pub fn guests(&self) -> Vec<Rc<Person>> {
match &self.tavern {
Some(tavern) => {
let loc = self.world.get_tavern_location(tavern);
self.people.iter().filter(|person| {
person.location == loc
}).map(|p| p.clone()).collect()
},
None => Vec::new(),
}
}
/**
* Function to populate the world at genesis
*/
pub fn found_town(&mut self) {
let mut rng = rand::thread_rng();
loop {
let x = rng.gen_range(0..self.world.size);
let y = rng.gen_range(0..self.world.size);
if
self.world.map[x][y].terrain == Terrain::Flats ||
self.world.map[x][y].terrain == Terrain::Hills
{
let town = Rc::new(Town::new());
self.add_event(Event {
time: self.time,
effect: Box::new(FoundTown {
x: x,
y: y,
town: town.clone(),
})
});
let pop_size = rng.gen_range(20..200);
for _ in 0..pop_size {
self.add_event(Event {
time: self.time,
effect: Box::new(PersonGenesis {
town: town.clone(),
person: Rc::new(Person::new(
self.time.substract_years(rng.gen_range(18..30)),
town.clone(),
self.world.get_town_location(&town)
)),
})
});
}
break;
}
}
}
pub fn add_person(&mut self, person: Rc<Person>) {
self.people.push(person);
}
pub fn build_tavern(&mut self) {
let mut rng = rand::thread_rng();
loop {
let x = rng.gen_range(0..self.world.size);
let y = rng.gen_range(0..self.world.size);
if
self.world.map[x][y].terrain == Terrain::Flats ||
self.world.map[x][y].terrain == Terrain::Hills
{
self.add_event(Event {
time: self.time,
effect: Box::new(TavernBuilt {
x: x,
y: y,
tavern: Rc::new(Tavern::new()),
})
});
}
}
}
}