Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main() {
- let mut player = Actor {
- data: ActorData {
- name: String::from("George"),
- position: Point(0, 0),
- },
- ai: ExampleAI {},
- };
- let mut npc = Actor {
- data: ActorData {
- name: String::from("Karen"),
- position: Point(3, 0),
- },
- ai: ExampleAI {},
- };
- let mut actors = vec![player, npc];
- // Need to update actors in a loop, each actor needs to access its own data and work with other actors.
- loop {
- // This seems like it'd work except for recursive type arguments.
- let mut cur_actor = actors.pop().unwrap();
- cur_actor.ai.update(&mut cur_actor.data, &mut actors);
- actors.insert(0, cur_actor);
- /* // This doesn't work, too many borrows.
- for actor in actors {
- actor.ai.update(&mut actor.data, &mut actors);
- }
- */
- }
- }
- struct Point(i32, i32);
- struct ActorData {
- name: String,
- position: Point,
- hp: i32,
- }
- struct Actor<T: AI> {
- data: ActorData,
- ai: T,
- }
- trait AI {
- fn update(&self, actor: &mut ActorData, others: &mut Vec<Actor>); // Actor needs a type argument now because of the generic AI.
- fn attack(&self) -> i32;
- fn defend(&mut self, incoming: i32);
- }
- struct ExampleAI {}
- impl AI for ExampleAI {
- fn update(&self, actor: &mut ActorData, others: &mut Vec<Actor>) {
- actor.position.0 += 1;
- let enemy = others[0];
- let damage = self.attack();
- enemy.defend(damage);
- }
- fn attack(&self) -> i32 {
- 10 // Damage dealt when attacking
- }
- fn defend(&mut self, incoming: i32) {
- self.data.hp -= incoming/2; // Damage received when attacked.
- }
- }
Add Comment
Please, Sign In to add comment