2 * The MIT License (MIT)
4 * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 package org.apidesign.html.demo.chess;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.Timer;
30 import java.util.TimerTask;
31 import net.java.html.json.ComputedProperty;
32 import net.java.html.json.Function;
33 import net.java.html.json.Model;
34 import net.java.html.json.ModelOperation;
35 import net.java.html.json.OnPropertyChange;
36 import net.java.html.json.Property;
37 import net.java.html.sound.AudioClip;
39 @Model(className="Board", properties={
40 @Property(name = "player", type = String.class),
41 @Property(name = "gameId", type = String.class),
42 @Property(name = "whitePlayer", type = String.class),
43 @Property(name = "blackPlayer", type = String.class),
44 @Property(name = "alertMessage", type = String.class),
45 @Property(name = "status", type = String.class),
46 @Property(name = "rows", type = Row.class, array = true),
47 @Property(name = "turn", type = Color.class),
48 @Property(name = "moves", type = Move.class, array = true),
49 @Property(name = "pendingMove", type = Move.class),
50 @Property(name = "active", type = boolean.class),
52 public class BoardModel {
53 @ComputedProperty static String title(String status, String gameId) {
54 String t = status != null ? status : gameId;
55 if (t != null && t.length() > 10) {
56 return t.substring(0, 10);
61 @ModelOperation static void updateSummary(Board b, String summary) {
62 if (summary != null) {
67 @ComputedProperty static boolean myTurn(String player, String whitePlayer, String blackPlayer, Color turn) {
68 if (turn != null && player != null) switch (turn) {
69 case B: return player.equals(blackPlayer);
70 case W: return player.equals(whitePlayer);
75 @ComputedProperty static boolean justObserving(String player) {
76 return player == null;
79 private static final AudioClip MOVE = AudioClip.create("sounds/move.mp3");
80 @OnPropertyChange("moves") static void playMove() {
84 private static final AudioClip CHECK = AudioClip.create("sounds/check.mp3");
85 private static final AudioClip CHECKMATE = AudioClip.create("sounds/checkmate.mp3");
87 @Function static void selected(Board b, Square data) {
89 b.setAlertMessage("Not your turn!");
93 Square previoslySelected = findSelectedSquare(b);
94 if (previoslySelected == null) {
95 if (data.getPiece() != null && data.getPieceColor() == b.getTurn()) {
96 data.setSelected(true);
97 Rules.computeAccessible(b, data);
100 if (previoslySelected == data) {
101 data.setSelected(false);
102 Rules.computeAccessible(b, null);
105 if (data.getPiece() != null && data.getPieceColor() == previoslySelected.getPieceColor()) {
106 previoslySelected.setSelected(false);
107 data.setSelected(true);
108 Rules.computeAccessible(b, data);
111 if (data.isAccessible()) {
112 previoslySelected.setSelected(false);
114 Move newMove = new Move();
115 newMove.setFrom(previoslySelected.getPosition());
116 newMove.setTo(data.getPosition());
117 newMove.setRound(b.getMoves().size() / 2 + 1);
118 newMove.setPiece(previoslySelected.getPiece());
119 newMove.setTurn(previoslySelected.getPieceColor());
120 newMove.setTakes(data.getPiece() != null);
121 b.getMoves().add(newMove);
122 b.setPendingMove(newMove);
124 data.setPending(true);
125 data.setPieceColor(previoslySelected.getPieceColor());
126 data.setPiece(previoslySelected.getPiece());
128 previoslySelected.setPiece(null);
129 previoslySelected.setPieceColor(null);
130 Rules.computeAccessible(b, null);
135 static class NextMove extends TimerTask {
136 private static final Timer T = new Timer("Animate moves");
137 private final Board b;
138 private final Move m;
140 public NextMove(Board b, Move m) {
143 T.schedule(this, 1000);
153 @ModelOperation @Function static void showPosition(Board b, Move data) {
155 boolean found = false;
156 for (Move m : b.getMoves()) {
162 Square from = findSquare(b, (char)m.getFrom().getX(), m.getFrom().getY());
163 Square to = findSquare(b, (char)m.getTo().getX(), m.getTo().getY());
164 to.setPiece(from.getPiece());
165 to.setPieceColor(from.getPieceColor());
167 from.setPieceColor(null);
172 b.setTurn(b.getMoves().size() % 2 == 0 ? Color.W : Color.B);
177 @Function static void rotateBoard(Board b) {
178 Collections.reverse(b.getRows());
179 for (Row r : b.getRows()) {
180 Collections.reverse(r.getColumns());
182 Square sq = findSelectedSquare(b);
184 sq.setSelected(false);
185 Rules.computeAccessible(b, null);
189 @ComputedProperty static boolean whiteTurn(Color turn) {
190 return turn == Color.W;
193 @ComputedProperty static boolean blackTurn(Color turn) {
194 return turn == Color.B;
197 @ComputedProperty static List<String> columnNames(List<Row> rows) {
198 boolean whiteDown = rows.isEmpty() || rows.get(0).getY() == 8;
199 String[] arr = new String[8];
200 for (int i = 0; i < 8; i++) {
203 s = "" + (char)('A' + i);
205 s = "" + (char)('H' - i);
209 return Arrays.asList(arr);
212 static Square findSquare(Board b, char column, int row) {
213 for (Row r : b.getRows()) {
214 for (Square square : r.getColumns()) {
215 if (square.getPosition().getX() == column && square.getPosition().getY() == row) {
223 private static Square findSquare(Board b, Position to) {
224 return findSquare(b, (char)to.getX(), to.getY());
227 static Square findSelectedSquare(Board b) {
228 for (Row row : b.getRows()) {
229 for (Square square : row.getColumns()) {
230 if (square.isSelected()) {
238 static void moveResponse(
239 final Board b, final String errMsg,
240 final List<String> whites, final List<String> blacks,
241 final Color turn, Object alert
243 if (errMsg != null) {
244 b.getMoves().remove(b.getPendingMove());
245 b.setPendingMove(null);
246 b.setAlertMessage(errMsg);
249 b.setAlertMessage(null);
251 Rules.initBoard(b, whites, blacks, turn);
254 static void moveUpdate(
255 final Board b, final Move move,
256 final List<String> whites, final List<String> blacks,
257 final Color turn, Object alert
259 final Square from = BoardModel.findSquare(b, move.getFrom());
260 final Square to = BoardModel.findSquare(b, move.getTo());
261 move.setPiece(from.getPiece());
262 move.setTurn(from.getPieceColor());
263 if (to.getPiece() != null) {
266 move.setRound(b.getMoves().size() / 2 + 1);
267 b.getMoves().add(move);
268 Rules.initBoard(b, whites, blacks, turn);
271 @Model(className="Row", properties = {
272 @Property(name = "columns", type = Square.class, array = true)
274 static class RowsImpl {
275 @ComputedProperty static int y(List<Square> columns) {
276 return columns.isEmpty() ? 0 : columns.get(0).getY();
281 PAWN(5), ROCK(2), KNIGHT(4), BISHOP(3), QUEEN(1), KING(0);
283 final int entityIndex;
286 this.entityIndex = ei;
289 static PieceType fromNotation(char notation) {
291 case 'R': return ROCK;
292 case 'N': return KNIGHT;
293 case 'B': return BISHOP;
294 case 'Q': return QUEEN;
295 case 'K': return KING;
296 case 'P': return PAWN;
298 throw new IllegalStateException("Unexpected: " + notation);
301 String computeEntity(Color color) {
307 case W: base = 12; break;
308 case B: base = 18; break;
310 throw new AssertionError();
312 return "b" + String.valueOf(base + entityIndex) + ";";
316 @Model(className="Position", properties = {
317 @Property(name = "x", type = char.class),
318 @Property(name = "y", type = int.class),
320 static class PositionImpl {
321 @ComputedProperty static String location(int x, int y) {
322 return "" + (char)(x - 'A' + 'a') + y;
326 @Model(className="Square", properties = {
327 @Property(name = "position", type = Position.class),
328 @Property(name = "color", type = Color.class),
329 @Property(name = "piece", type = PieceType.class),
330 @Property(name = "pieceColor", type = Color.class),
331 @Property(name = "selected", type = boolean.class),
332 @Property(name = "accessible", type = boolean.class),
333 @Property(name = "pending", type = boolean.class),
335 static class SquareModel {
336 @ComputedProperty static String pieceEntity(
337 PieceType piece, Color pieceColor
342 return piece.computeEntity(pieceColor);
345 @ComputedProperty static String squareColor(
346 Color color, boolean selected, boolean accessible, boolean pending
361 if (color == Color.W) {
369 @ComputedProperty static char x(Position position) {
370 return position == null ? 'A' : position.getX();
373 @ComputedProperty static int y(Position position) {
374 return position == null ? 1 : position.getY();
378 @Model(className = "Move", properties = {
379 @Property(name = "round", type = int.class),
380 @Property(name = "turn", type = Color.class),
381 @Property(name = "piece", type = PieceType.class),
382 @Property(name = "from", type = Position.class),
383 @Property(name = "to", type = Position.class),
384 @Property(name = "promoted", type = PieceType.class),
385 @Property(name = "takes", type = boolean.class),
386 @Property(name = "check", type = boolean.class),
388 static class MoveImpl {
389 @ComputedProperty static boolean whiteMove(Color turn) {
390 return turn == Color.W;
393 @ComputedProperty static String html(
394 Position from, Position to, boolean takes, PieceType piece, Color turn
396 if (from == null || to == null) {
399 StringBuilder sb = new StringBuilder();
400 if (piece != null && piece != PieceType.PAWN) {
401 sb.append(piece.computeEntity(turn));
404 sb.append(from.getLocation());
408 sb.append(to.getLocation());
409 return sb.toString();
412 static Move valueOf(String move) {
413 move = move.toUpperCase();
416 Position p = new Position();
417 p.setX(move.charAt(0));
418 p.setY(move.charAt(1) - '0');
422 Position p = new Position();
423 p.setX(move.charAt(2));
424 p.setY(move.charAt(3) - '0');