/army/h1/x_front.erl

http://erlbattle.googlecode.com/ · Erlang · 73 lines · 53 code · 20 blank · 0 comment · 0 complexity · 329aa08c0e5517efef6deba20051b992 MD5 · raw file

  1. -module(h1.x_front).
  2. -behaviour(gen_fsm).
  3. -compile(export_all).
  4. -include("schema.hrl").
  5. -include("def.hrl").
  6. -export([init/1, handle_event/3, terminate/3]).
  7. -record(data,
  8. {
  9. last_score = -1
  10. }
  11. ).
  12. start_link(ID, Phone) ->
  13. .gen_fsm:start_link(?MODULE, {self(), ID, Phone}, []).
  14. init({Master, ID, Phone}) ->
  15. put(master, Master),
  16. {ok, state_detecting, {ID, Phone, #data{}}, 1}.
  17. state_detecting(timeout, {ID, Phone, Data}) ->
  18. Soldiers = get_front(ID, Phone),
  19. NewData = notify_detect_result(Soldiers, Data),
  20. h1.util:next_detect_state(Soldiers, state_detecting, {ID, Phone, NewData});
  21. state_detecting(set_control, StateData) ->
  22. {next_state, state_fighting, StateData, 1}.
  23. get_front(ID, Phone) ->
  24. h1.util:get_enemy(ID, Phone,
  25. fun(#soldier{facing = Facing}) ->
  26. [h1.util:forward(Facing, 1), h1.util:forward(Facing, 2)]
  27. end,
  28. h1.util:friend_filter(Phone),
  29. fun(Soldier, E1, E2) ->
  30. Dist1 = h1.util:dist(Soldier, E1),
  31. Dist2 = h1.util:dist(Soldier, E2),
  32. Dist1 =< Dist2
  33. end).
  34. notify_detect_result(Soldiers, Data) ->
  35. OldScore = Data#data.last_score,
  36. NewScore = h1.util:notify_detect_result(Soldiers, OldScore, ?X_Front_Score),
  37. Data#data{ last_score = NewScore }.
  38. state_fighting(timeout, {ID, Phone, Data}) ->
  39. Soldiers = get_front(ID, Phone),
  40. attack_front(ID, Soldiers, Phone),
  41. NewData = notify_detect_result(Soldiers, Data),
  42. h1.util:next_detect_state(Soldiers, state_fighting, {ID, Phone, NewData});
  43. state_fighting(lost_control, StateData) ->
  44. {next_state, state_detecting, StateData, 1}.
  45. attack_front(_ID, idead, _Phone) ->
  46. noaction;
  47. attack_front(_ID, none, _Phone) ->
  48. noaction;
  49. attack_front(ID, _Soldiers, #phone{channel = Channel}) ->
  50. Channel ! {command, ?ActionAttack, ID, 0, 0}.
  51. handle_event(stop, _StateName, StateData) ->
  52. {stop, shutdown, StateData}.
  53. terminate(_, _, _) -> ok.