1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00
chess/web/controllers/api/game_controller.ex
Dan Barber 7ff1b03f89
Refactor the board data structure
Now we're only storing the pieces keyed by the piece position rather
than storing the entire board as a set of nested Maps. This makes moving
pieces much easier. We're also now storing the position as a pair of
array indices which should make calculating the possible moves easier.
2017-01-18 16:36:38 +00:00

31 lines
771 B
Elixir

defmodule Chess.Api.GameController do
use Chess.Web, :controller
require Logger
alias Chess.Game
def show(conn, %{"id" => id}) do
game = Repo.get!(Game, id)
render conn, "show.json", game: game
end
def update(conn, %{"id" => id, "move" => move_params}) do
game = Repo.get!(Game, id)
changeset = Game.changeset(game, %{board: new_board(game.board, move_params)})
case Repo.update(changeset) do
{:ok, game} ->
render(conn, "show.json", game: game)
end
end
defp new_board(board, move_params) do
[from_file, from_rank] = move_params["from"]
[to_file, to_rank] = move_params["to"]
{piece, board} = Map.pop(board, "#{from_file},#{from_rank}")
Map.put(board, "#{to_file},#{to_rank}", piece)
end
end