-module(path).
-export([start/0]).
start()->
path_find({0,0},{15,23},[]). %%从{0,0}点走到点{15,23}
path_find(Begin,End,Path)->
{X,Y}=Begin,
{EndX,EndY}=End,
DeltaX=erlang:abs(2*(EndX-X)),
DeltaY=erlang:abs(2*(EndY-Y)),
if
DeltaX>DeltaY-> %%每走一步x肯定增大,但是y不一定增大
put(fraction,DeltaY*2-DeltaX),
NewPath=step_x(Begin,End,Path,DeltaX,DeltaY);
DeltaX=<DeltaY-> %%每走一步y肯定增大,但是x不一定增大
put(fraction,DeltaX*2-DeltaY),
NewPath=step_y(Begin,End,Path,DeltaX,DeltaY)
end,
%io:format("npc ai path is:~p~n",[NewPath]),
NewPath.
step_x(End,End,Path,_DeltaX,_DeltaY)->
Path;
step_x(Begin,End,Path,DeltaX,DeltaY)->
{X,Y}=Begin,
{EndX,EndY}=End,
Fraction=get(fraction),
if Fraction>=0->
NextY=Y+erlang:min(1,EndY-Y),
put(fraction,get(fraction)-DeltaX);
true->
NextY=Y
end,
NextX=X+erlang:min(1,EndX-X),
io:format("Next step is ~p ~p~n",[NextX,NextY]),
NewPath=lists:append(Path, [{NextX,NextY}]),
put(fraction,get(fraction)+DeltaY),
step_x({NextX,NextY},End,NewPath,DeltaX,DeltaY).
step_y(End,End,Path,_DeltaX,_DeltaY)->
Path;
step_y(Begin,End,Path,DeltaX,DeltaY)->
{X,Y}=Begin,
{EndX,EndY}=End,
Fraction=get(fraction),
if Fraction>=0->
NextX=X+erlang:min(1,EndX-X),
put(fraction,get(fraction)-DeltaX);
true->
NextX=X
end,
NextY=Y+erlang:min(1,EndY-Y),
%io:format("Next step is ~p ~p~n",[NextX,NextY]),
NewPath=lists:append(Path,[{NextX,NextY}]),
put(fraction,get(fraction)+DeltaX),
step_y({NextX,NextY},End,NewPath,DeltaX,DeltaY).