Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(reversi).
- -export([empty/0,update/2,open/0,find_legal_moves/2]).
- empty() ->
- Row=lists:duplicate(8,'.'),
- lists:duplicate(8,Row).
- index(XS) ->
- [{I,X}||{I,X}<-lists:zip(lists:seq(1,length(XS)),XS)].
- update(Board,Disks) ->
- UpdateSquare=fun(ColI,RowI,OldValue) ->
- Found=[Disk||{X,Y,Disk}<-Disks,X==ColI,Y==RowI],
- case Found of [Disk] -> Disk; [] -> OldValue end
- end,
- [[UpdateSquare(ColI,RowI,Value)
- ||{ColI,Value}<-index(Row)]
- ||{RowI,Row}<-index(Board)].
- open() ->
- update(empty(),[{4,4,'W'},{5,4,'B'},{4,5,'B'},{5,5,'W'}]).
- is_out_of_bounds(X,_) when X<1 orelse X>8 -> true;
- is_out_of_bounds(_,Y) when Y<1 orelse Y>8 -> true;
- is_out_of_bounds(_,_) -> false.
- at(Board,X,Y) ->
- Row=lists:nth(Y,Board),
- lists:nth(X,Row).
- find_legal_move(Board,{StartX,StartY},{DX,DY},Disk,Count) ->
- X = StartX + DX, Y = StartY + DY,
- Out=is_out_of_bounds(X,Y),
- if
- Out -> false;
- not Out ->
- Value=at(Board,X,Y),
- case Value of
- '.' when Count > 0 -> {X,Y};
- Disk -> find_legal_move(Board,{X,Y},{DX,DY},Disk,Count+1);
- _ -> false
- end
- end.
- find_legal_moves_at(Board,{X,Y}) ->
- Disk=case at(Board,X,Y) of 'W' -> 'B'; 'B' -> 'W' end,
- Vectors=
- [{-1,-1},{0,-1},{ 1,-1},
- {-1, 0}, { 1, 0},
- {-1, 1},{0, 1},{ 1, 1}],
- Results=[find_legal_move(Board,{X,Y},{DX,DY},Disk,0)||{DX,DY}<-Vectors],
- lists:filter(fun(R)->if R==false -> false; true -> true end end,Results).
- find_disks(Board, Disk) ->
- lists:flatten([
- [{ColI,RowI}||{ColI,Value}<-index(Row), Value==Disk]
- ||{RowI,Row}<-index(Board)
- ]).
- find_legal_moves(Board,Disk) ->
- [find_legal_moves_at(Board,Pos)||Pos<-find_disks(Board, Disk)].
Advertisement
Add Comment
Please, Sign In to add comment