common.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Helpers
  2. def state_of(od, animal):
  3. return od.get_source(od.get_incoming(animal, "of")[0])
  4. def animal_of(od, state):
  5. return od.get_target(od.get_outgoing(state, "of")[0])
  6. def get_time(od):
  7. _, clock = od.get_all_instances("Clock")[0]
  8. return clock, od.get_slot_value(clock, "time")
  9. # Render our run-time state to a string
  10. def render_woods(od):
  11. txt = ""
  12. _, time = get_time(od)
  13. txt += f"T = {time}.\n"
  14. txt += "Bears:\n"
  15. def render_attacking(animal_state):
  16. attacking = od.get_outgoing(animal_state, "attacking")
  17. if len(attacking) == 1:
  18. whom_state = od.get_target(attacking[0])
  19. whom_name = od.get_name(animal_of(od, whom_state))
  20. return f" attacking {whom_name}"
  21. else:
  22. return ""
  23. def render_dead(animal_state):
  24. return 'dead' if od.get_slot_value(animal_state, 'dead') else 'alive'
  25. for _, bear_state in od.get_all_instances("BearState"):
  26. bear = animal_of(od, bear_state)
  27. hunger = od.get_slot_value(bear_state, "hunger")
  28. txt += f" 🐻 {od.get_name(bear)} (hunger: {hunger}, {render_dead(bear_state)}) {render_attacking(bear_state)}\n"
  29. txt += "Men:\n"
  30. for _, man_state in od.get_all_instances("ManState"):
  31. man = animal_of(od, man_state)
  32. attacked_by = od.get_incoming(man_state, "attacking")
  33. if len(attacked_by) == 1:
  34. whom_state = od.get_source(attacked_by[0])
  35. whom_name = od.get_name(animal_of(od, whom_state))
  36. being_attacked = f" being attacked by {whom_name}"
  37. else:
  38. being_attacked = ""
  39. txt += f" 👨 {od.get_name(man)} ({render_dead(man_state)}) {render_attacking(man_state)}{being_attacked}\n"
  40. return txt
  41. # When should simulation stop?
  42. def termination_condition(od):
  43. _, time = get_time(od)
  44. if time >= 10:
  45. return "Took too long"
  46. # End simulation when 2 animals are dead
  47. who_is_dead = []
  48. for _, animal_state in od.get_all_instances("AnimalState"):
  49. if od.get_slot_value(animal_state, "dead"):
  50. animal_name = od.get_name(animal_of(od, animal_state))
  51. who_is_dead.append(animal_name)
  52. if len(who_is_dead) >= 2:
  53. return f"{' and '.join(who_is_dead)} are dead"