From 8b6811d13aebc7a5113fb53d9258b33833a75f06 Mon Sep 17 00:00:00 2001 From: Rob Whittaker Date: Fri, 9 Dec 2016 16:02:15 +0000 Subject: [PATCH] Update with fucking moves --- web/controllers/api/game_controller.ex | 26 +++++++++++++++++-- .../js/components/chess-board-square.js | 16 ++++++++---- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/web/controllers/api/game_controller.ex b/web/controllers/api/game_controller.ex index bca1e31..9b03e56 100644 --- a/web/controllers/api/game_controller.ex +++ b/web/controllers/api/game_controller.ex @@ -8,9 +8,9 @@ defmodule Chess.Api.GameController do render conn, "show.json", game: game end - def update(conn, %{"id" => id, "game" => game_params}) do + def update(conn, %{"id" => id, "move" => move_params}) do game = Repo.get!(Game, id) - changeset = Game.changeset(game, game_params) + changeset = Game.changeset(game, %{ board: new_board(game, move_params) }) case Repo.update(changeset) do {:ok, game} -> @@ -19,4 +19,26 @@ defmodule Chess.Api.GameController do render(conn, "edit.html", game: game, changeset: changeset) end end + + defp new_board(game, move_params) do + game.board + |> put_in(move(move_from(move_params)), nil) + |> put_in(move(move_to(move_params)), piece(game, move_params)) + end + + defp move_from(move) do + move["from"] + end + + defp move(square) do + [square["rank"], square["file"]] + end + + defp piece(game, move) do + get_in(game.board, move(move_from(move))) + end + + defp move_to(move) do + move["to"] + end end diff --git a/web/static/js/components/chess-board-square.js b/web/static/js/components/chess-board-square.js index cfac45b..3188bd1 100644 --- a/web/static/js/components/chess-board-square.js +++ b/web/static/js/components/chess-board-square.js @@ -16,13 +16,19 @@ class ChessBoardSquare extends React.Component { } selectSquare() { - var { store } = this.props; + var { piece, store } = this.props; + var { gameId, selectedSquare } = store.getState(); - if (store.getState().selectedSquare != null) { - store.dispatch(movePiece(store.getState().selectedSquare, this.squareCoords())); - $.ajax({ method: "PATCH", url: "/api/games/" + store.getState().gameId, data: { game: { board: store.getState().board } }}); + if (selectedSquare != null) { + store.dispatch(movePiece(selectedSquare, this.squareCoords())); + + $.ajax({ + method: "PATCH", + url: "/api/games/" + gameId, + data: { move: { from: selectedSquare, to: this.squareCoords() } } + }); } - else if (this.props.piece != undefined) { + else if (piece != undefined) { store.dispatch(selectPiece(this.squareCoords())); } };