PageRenderTime 85ms CodeModel.GetById 72ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/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
 8
 9-record(data,
10	{
11		last_score = -1
12	}
13).
14
15
16start_link(ID, Phone) ->
17	.gen_fsm:start_link(?MODULE, {self(), ID, Phone}, []).
18
19
20init({Master, ID, Phone}) ->
21	put(master, Master),
22	{ok, state_detecting, {ID, Phone, #data{}}, 1}.
23
24
25state_detecting(timeout, {ID, Phone, Data}) ->
26	Soldiers = get_front(ID, Phone),
27	NewData = notify_detect_result(Soldiers, Data),
28	h1.util:next_detect_state(Soldiers, state_detecting, {ID, Phone, NewData});
29state_detecting(set_control, StateData) ->
30	{next_state, state_fighting, StateData, 1}.
31
32
33get_front(ID, Phone) ->
34	h1.util:get_enemy(ID, Phone,
35		fun(#soldier{facing = Facing}) ->
36				[h1.util:forward(Facing, 1), h1.util:forward(Facing, 2)]
37		end,
38		h1.util:friend_filter(Phone),
39		fun(Soldier, E1, E2) ->
40			Dist1 = h1.util:dist(Soldier, E1),
41			Dist2 = h1.util:dist(Soldier, E2),
42			Dist1 =< Dist2
43		end).
44
45
46notify_detect_result(Soldiers, Data) ->
47	OldScore = Data#data.last_score,
48	NewScore = h1.util:notify_detect_result(Soldiers, OldScore, ?X_Front_Score),
49	Data#data{ last_score = NewScore }.
50
51
52state_fighting(timeout, {ID, Phone, Data}) ->
53	Soldiers = get_front(ID, Phone),
54	attack_front(ID, Soldiers, Phone),
55	NewData = notify_detect_result(Soldiers, Data),
56	h1.util:next_detect_state(Soldiers, state_fighting, {ID, Phone, NewData});
57state_fighting(lost_control, StateData) ->
58	{next_state, state_detecting, StateData, 1}.
59
60
61attack_front(_ID, idead, _Phone) ->
62	noaction;
63attack_front(_ID, none, _Phone) ->
64	noaction;
65attack_front(ID, _Soldiers, #phone{channel = Channel}) ->
66	Channel ! {command, ?ActionAttack, ID, 0, 0}.
67
68
69handle_event(stop, _StateName, StateData) ->
70	{stop, shutdown, StateData}.
71
72
73terminate(_, _, _) -> ok.