Skip to content

Commit

Permalink
Position islands
Browse files Browse the repository at this point in the history
  • Loading branch information
jrowah committed Dec 30, 2023
1 parent 4fab9af commit 1446571
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion lib/islands_engine/game.ex
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
defmodule IslandEngine.Game do
alias IslandsEngine.{Board, Guesses}
alias IslandsEngine.{Board, Coordinate, Guesses, Island}
alias IslandEngine.Rules

use GenServer

@players [:player1, :player2]

def start_link(name) when is_binary(name), do: GenServer.start_link(__MODULE__, name, [])

def init(name) do
Expand All @@ -13,6 +16,9 @@ defmodule IslandEngine.Game do

def add_player(game, name) when is_binary(name), do: GenServer.call(game, {:add_player, name})

def position_island(game, player, key, row, col) when player in @players,
do: GenServer.call(game, {:position_island, player, key, row, col})

def handle_call({:add_player, name}, _from, state_data) do
with {:ok, rules} <- Rules.check(state_data.rules, :add_player) do
state_data
Expand All @@ -24,9 +30,45 @@ defmodule IslandEngine.Game do
end
end

def handle_call({:position_island, player, key, row, col}, _from, state_data) do
board = player_board(state_data, player)
IO.inspect(board)

with {:ok, rules} <- Rules.check(state_data.rules, :position_island),
{:ok, coordinate} <- Coordinate.new(row, col),
{:ok, island} <- Island.new(key, coordinate),
%{} = board <- Board.position_island(board, key, island) do
IO.inspect("Grut")

state_data
|> update_board(player, board)
|> update_rules(rules)
|> reply_success(:ok)
else
:error ->
{:reply, :error, state_data}

{:error, :invalid_coordinate} ->
{:reply, {:error, :invalid_coordinate}, state_data}

{:error, :invalid_island_type} ->
{:error, {:error, :invalid_island_type}, state_data}

{:error, :overlapping_island} ->
{:error, {:error, :overlapping_island}, state_data}

IO.inspect("Else Grut")
end
end

defp update_player2_name(state_data, name), do: put_in(state_data.player2.name, name)

defp update_rules(state_data, rules), do: %{state_data | rules: rules}

defp reply_success(state_data, reply), do: {:reply, reply, state_data}

defp update_board(state_data, player, board),
do: Map.update!(state_data, player, fn player -> %{player | board: board} end)

defp player_board(state_data, player), do: Map.get(state_data, player).board
end

0 comments on commit 1446571

Please sign in to comment.