Guest User

Untitled

a guest
Jun 24th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. fn main() {
  2. let mut player = Actor {
  3. data: ActorData {
  4. name: String::from("George"),
  5. position: Point(0, 0),
  6. },
  7. ai: ExampleAI {},
  8. };
  9.  
  10. let mut npc = Actor {
  11. data: ActorData {
  12. name: String::from("Karen"),
  13. position: Point(3, 0),
  14. },
  15. ai: ExampleAI {},
  16. };
  17.  
  18. let mut actors = vec![player, npc];
  19.  
  20. // Need to update actors in a loop, each actor needs to access its own data and work with other actors.
  21.  
  22. loop {
  23. // This seems like it'd work except for recursive type arguments.
  24. let mut cur_actor = actors.pop().unwrap();
  25. cur_actor.ai.update(&mut cur_actor.data, &mut actors);
  26. actors.insert(0, cur_actor);
  27.  
  28. /* // This doesn't work, too many borrows.
  29. for actor in actors {
  30. actor.ai.update(&mut actor.data, &mut actors);
  31. }
  32. */
  33. }
  34. }
  35.  
  36. struct Point(i32, i32);
  37.  
  38. struct ActorData {
  39. name: String,
  40. position: Point,
  41. hp: i32,
  42. }
  43.  
  44. struct Actor<T: AI> {
  45. data: ActorData,
  46. ai: T,
  47. }
  48.  
  49. trait AI {
  50. fn update(&self, actor: &mut ActorData, others: &mut Vec<Actor>); // Actor needs a type argument now because of the generic AI.
  51. fn attack(&self) -> i32;
  52. fn defend(&mut self, incoming: i32);
  53. }
  54.  
  55. struct ExampleAI {}
  56.  
  57. impl AI for ExampleAI {
  58. fn update(&self, actor: &mut ActorData, others: &mut Vec<Actor>) {
  59. actor.position.0 += 1;
  60. let enemy = others[0];
  61. let damage = self.attack();
  62. enemy.defend(damage);
  63. }
  64.  
  65. fn attack(&self) -> i32 {
  66. 10 // Damage dealt when attacking
  67. }
  68.  
  69. fn defend(&mut self, incoming: i32) {
  70. self.data.hp -= incoming/2; // Damage received when attacked.
  71. }
  72. }
Add Comment
Please, Sign In to add comment