Skip to content

Instantly share code, notes, and snippets.

@danielerapati
Created January 19, 2016 21:54
Show Gist options
  • Save danielerapati/78949b374410dc1f9e47 to your computer and use it in GitHub Desktop.
Save danielerapati/78949b374410dc1f9e47 to your computer and use it in GitHub Desktop.
Erlang battleship: January 2016 West London Hacknight
-module(battleship).
-import(sets,[new/0, add_element/2, is_element/2]).
-import(lists,[foldl/3]).
-export([new_grid/0]).
-export([new_grid/2]).
-export([fill_cell/2]).
-export([random_placement/1]).
-export([guess_cell/2]).
-export([shoot_one/3]).
-export([print/1]).
-export([print_cell/2]).
new_grid() -> new_grid(10,10).
new_grid(H,L) -> sets:new().
fill_cell(Location, Grid) ->
C = sets:is_element(Location, Grid),
if C -> notok;
true -> sets:add_element(Location, Grid)
end.
guess_cell(Location, Grid) -> sets:is_element(Location, Grid).
random_placement(Grid) -> lists:foldl(fun battleship:fill_cell/2, Grid,[{'A',1}, {'B',1}, {'C',1}, {'D',1}]).
shoot_one(Location, Current_view, Grid) ->
C = guess_cell(Location, Grid),
if C -> dict:append(Location, true, Current_view);
true -> dict:append(Location, false, Current_view)
end.
print_cell(Cel, Grid) ->
C = dict:find(Cel, Grid),
case C of error -> "_";
{ok, [true]} -> "X";
_ -> "."
end.
print(View) ->
io:fwrite(
string:join([
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'A',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'B',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'C',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'D',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'E',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'F',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'G',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'H',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'I',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),""),
string:join(lists:map(fun(L)->battleship:print_cell(L,View) end, [{'J',X} || X <- [1,2,3,4,5,6,7,8,9,10]]),"")
],io_lib:format("\n",[]))).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment