Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When designing software, I find it helpful to think about how I would use a method, then write down the method signature (and if you do test driven development, the unit test), and only then think about how I would implement it.</p> <p>Doing this here, I find that the requirement</p> <blockquote> <p>Then when a player clicks a piece, the squares that are available as destination after the move will be outlined in some colour.</p> </blockquote> <p>is impossible to satisfy with a method like</p> <pre><code>void move(Square destination); </code></pre> <p>because there is no way to find out the possible moves without actually making them. To highlight the squares, it would probably be best if we had a method like</p> <pre><code>Collection&lt;Square&gt; getPossibleMoves(); </code></pre> <p>and then we could implement</p> <pre><code>void move(Square destination) { if (!getPossibleMoves().contains(destination) { throw new IllegalMoveException(); } this.location.occupyingPiece = null; this.location = destination; this.location.occupyingPiece = this; } </code></pre> <p>as for implementing getPossibleMoves:</p> <pre><code>class Pawn extends Piece { @Override Collection&lt;Square&gt; getPossibleMoves() { List&lt;Square&gt; possibleMoves = new ArrayList&lt;Square&gt;(); int dy = color == Color.white ? 1 : -1; Square ahead = location.neighbour(0, dy); if (ahead.occupyingPiece == null) { possibleMoves.add(ahead); } Square aheadLeft = location.neighbour(-1, dy); if (aheadLeft != null &amp;&amp; aheadLeft.occupyingPiece != null &amp;&amp; aheadLeft.occupyingPiece.color != color) { possibleMoves.add(aheadLeft); } Square aheadRight = location.neighbour(1, dy); if (aheadRight != null &amp;&amp; aheadRight.occupyingPiece != null &amp;&amp; aheadRight.occupyingPiece.color != color) { possibleMoves.add(aheadRight); } return possibleMoves; } } </code></pre> <p><strong>Edit</strong>:</p> <pre><code>class Knight extends Piece { @Override Collection&lt;Square&gt; getPossibleMoves() { List&lt;Square&gt; possibleMoves = new ArrayList&lt;Square&gt;(); int[][] offsets = { {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} }; for (int[] o : offsets) { Square candidate = location.neighbour(o[0], o[1]); if (candidate != null &amp;&amp; (candidate.occupyingPiece == null || candidate.occupyingPiece.color != color)) { possibleMoves.add(candidate); } } return possibleMoves; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload