Browse files

updated canvas client sample

  • Loading branch information...
1 parent e2c760d commit d0519537e831e17d6d71ae7b23788c00835d2b68 @financeCoding committed Jul 16, 2012
View
47 Engine/Engine.dart
@@ -52,10 +52,29 @@ class Engine {
{
return false;
}
-
+
return ChessBoard.Squares[index].PlacedPiece.Selected;
}
+ Map GetCurrentPieceSelected() {
+ var ret_map = {}; // TODO: refactor this into a real structure
+ for (int i=0; i<8; i++) {
+ for (int j=0; j<8; j++) {
+ if (GetChessPieceSelected(i, j)) {
+ int index = _GetBoardIndex(i, j);
+
+ ret_map["col"] = i;
+ ret_map["row"] = j;
+ ret_map["piece"] = ChessBoard.Squares[index].PlacedPiece;
+ //print("ret_map = ${ret_map}");
+ return ret_map;
+ }
+ }
+ }
+
+ return ret_map;
+ }
+
List<int> GetEnPassantMoves()
{
if (ChessBoard == null)
@@ -138,6 +157,32 @@ class Engine {
return returnArray;
}
+ bool IsSquareWhoseMove(int col, row) {
+ if (ChessBoard == null)
+ {
+ return false;
+ }
+
+ if (ChessBoard.Squares == null)
+ {
+ return false;
+ }
+
+ int index = _GetBoardIndex(col, row);
+
+ if (ChessBoard.Squares[index].PlacedPiece == null)
+ {
+ return false;
+ }
+
+ if (GetPieceColorAtIndex(index) == WhoseMove && GetPieceTypeAtIndex(index) != ChessPieceType.None) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
bool IsValidMove(int sourceColumn, int sourceRow, int destinationColumn, int destinationRow)
{
if (ChessBoard == null)
View
2 Engine/Piece.dart
@@ -12,7 +12,7 @@ class Piece {
int LastValidMoveCount;
bool Moved;
- bool Selected;
+ bool Selected = false;
List<int> ValidMoves;
View
93 samples/canvasclient/canvasclient/Board.dart
@@ -1,10 +1,12 @@
-
class Board {
+ ChessEngine.Engine engine;
CanvasRenderingContext2D ctx;
+ List<Piece> pieces;
int ratio;
int width;
int height;
+ BoardSquare selectedSquare;
Map<String, BoardSquare> highlightsquares;
Map<String, BoardSquare> squares;
Function piecemoves;
@@ -13,7 +15,7 @@ class Board {
final _boxColor1 = "rgb(0, 127, 0)";
final _boxColor2 = "rgb(251, 246, 229)";
- Board(this.ctx, [this.height = 400, this.width = 400]) {
+ Board(this.ctx, this.engine, [this.height = 400, this.width = 400]) {
ratio = (height / width).toInt();
highlightsquares = {};
squares = {};
@@ -38,20 +40,79 @@ class Board {
}
}
- void select(int x, int y) {
- BoardSquare boardsquare;
-
- squares.forEach((k, v) {
- if (v.contains(x, y)) {
- v.highlighted = true;
- boardsquare = v;
- } else {
- v.highlighted = false;
- }
- });
-
- if (boardsquare != null && piecemoves != null) {
- piecemoves(boardsquare);
+ void selectSquare(int x, int y) {
+ // This smells of state pattern
+ if (selectedSquare == null) {
+ squares.forEach((k, v) {
+ if (v.contains(x, y)) {
+
+ print("engine.IsSquareWhoseMove(v.col, v.row) = ${engine.IsSquareWhoseMove(v.col, v.row)}");
+ if (engine.IsSquareWhoseMove(v.col, v.row)) {
+ v.highlighted = true;
+ selectedSquare = v;
+ }
+ } else {
+ v.highlighted = false;
+ }
+ });
+ } else {
+ bool selectedSquareMoves = true;
+ var tmp_selectedSquare = null;
+ squares.forEach((k, v) {
+ if (v.contains(x, y)) {
+ if (engine.IsSquareWhoseMove(v.col, v.row)) {
+ v.highlighted = true;
+ tmp_selectedSquare = v;
+ selectedSquareMoves = false;
+ }
+ } else {
+ v.highlighted = false;
+ }
+ });
+
+ if (selectedSquareMoves == false && tmp_selectedSquare != null) {
+ selectedSquare = tmp_selectedSquare;
+ } else {
+ // possible attacking or move selected
+
+ BoardSquare dest_square;
+ squares.forEach((kk, vv) {
+ if (vv.contains(x, y)) {
+ dest_square = vv;
+ }
+ });
+
+ if (dest_square != null) {
+
+ bool validMove = engine.IsValidMove(selectedSquare.col, selectedSquare.row,
+ dest_square.col, dest_square.row);
+
+ print("validMove = ${validMove}");
+
+ if (validMove) {
+ bool moveSuccess = engine.MovePiece(selectedSquare.col, selectedSquare.row,
+ dest_square.col, dest_square.row);
+
+ print("selectedSquare.col = ${selectedSquare.col}");
+ print("selectedSquare.row = ${selectedSquare.row}");
+ print("dest_square.col = ${dest_square.col}");
+ print("dest_square.row = ${dest_square.row}");
+
+ String src_sq = Utils.toSquare(1 + selectedSquare.col, 8 - selectedSquare.row);
+ String dest_sq = Utils.toSquare(1 + dest_square.col, 8 - dest_square.row);
+ print("src_sq = ${src_sq}");
+ print("dest_sq = ${dest_sq}");
+
+ pieces.forEach((p){
+ if (p.sq == src_sq) {
+ print("setting p=${p} .sq = ${dest_sq}");
+ p.sq = dest_sq;
+ }
+ });
+
+ }
+ }
+ }
}
}
View
150 samples/canvasclient/canvasclient/canvasclient.dart
@@ -7,82 +7,100 @@
#source('PieceData.dart');
#source('utils.dart');
-num rotatePos = 0;
-
-void main() {
- CanvasElement canvas = query("#board");
- CanvasRenderingContext2D ctx = canvas.getContext("2d");
-
- ChessEngine.Engine engine = new ChessEngine.Engine();
-
- List components = [];
+class Game {
+ ChessEngine.Engine engine;
+ Board board;
+ List<Piece> pieces;
+ CanvasElement canvas;
+ CanvasRenderingContext2D _ctx;
+ int _ratio;
- Board b = new Board(ctx, height: canvas.height, width: canvas.width);
- b.piecemoves = (BoardSquare boardsquare) {
- List<List<int>> moves = engine.GetValidMoves(boardsquare.col, boardsquare.row);
-
- if (moves != null) {
- moves.forEach((sq) {
- b.highlight(sq[0], sq[1]);
- });
- }
- };
- b.draw();
-
- components.add(b);
-
- components.add(new Piece(b.ctx, b.ratio, "White King", PieceData.wk, "e1"));
- components.add(new Piece(b.ctx, b.ratio, "Black King", PieceData.bk, "e8"));
+ Game(this.canvas, this.engine) {
+ _ctx = canvas.getContext("2d");
+ board = new Board(_ctx, engine, height: canvas.height, width: canvas.width);
+ this._ratio = board.ratio;
+ pieces = [];
+ pieces.add(new Piece(_ctx, _ratio, "White King", PieceData.wk, "e1"));
+ pieces.add(new Piece(_ctx, _ratio, "Black King", PieceData.bk, "e8"));
- components.add(new Piece(b.ctx, b.ratio, "White Queen", PieceData.wq, "d1"));
- components.add(new Piece(b.ctx, b.ratio, "Black Queen", PieceData.bq, "d8"));
+ pieces.add(new Piece(_ctx, _ratio, "White Queen", PieceData.wq, "d1"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Queen", PieceData.bq, "d8"));
- components.add(new Piece(b.ctx, b.ratio, "White Bishop", PieceData.wb, "c1"));
- components.add(new Piece(b.ctx, b.ratio, "White Bishop", PieceData.wb, "f1"));
- components.add(new Piece(b.ctx, b.ratio, "Black Bishop", PieceData.bb, "c8"));
- components.add(new Piece(b.ctx, b.ratio, "Black Bishop", PieceData.bb, "f8"));
+ pieces.add(new Piece(_ctx, _ratio, "White Bishop", PieceData.wb, "c1"));
+ pieces.add(new Piece(_ctx, _ratio, "White Bishop", PieceData.wb, "f1"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Bishop", PieceData.bb, "c8"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Bishop", PieceData.bb, "f8"));
- components.add(new Piece(b.ctx, b.ratio, "White Knight", PieceData.wn, "b1"));
- components.add(new Piece(b.ctx, b.ratio, "White Knight", PieceData.wn, "g1"));
- components.add(new Piece(b.ctx, b.ratio, "Black Knight", PieceData.bn, "b8"));
- components.add(new Piece(b.ctx, b.ratio, "Black Knight", PieceData.bn, "g8"));
+ pieces.add(new Piece(_ctx, _ratio, "White Knight", PieceData.wn, "b1"));
+ pieces.add(new Piece(_ctx, _ratio, "White Knight", PieceData.wn, "g1"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Knight", PieceData.bn, "b8"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Knight", PieceData.bn, "g8"));
- components.add(new Piece(b.ctx, b.ratio, "White Rook", PieceData.wr, "a1"));
- components.add(new Piece(b.ctx, b.ratio, "White Rook", PieceData.wr, "h1"));
- components.add(new Piece(b.ctx, b.ratio, "Black Rook", PieceData.br, "a8"));
- components.add(new Piece(b.ctx, b.ratio, "Black Rook", PieceData.br, "h8"));
+ pieces.add(new Piece(_ctx, _ratio, "White Rook", PieceData.wr, "a1"));
+ pieces.add(new Piece(_ctx, _ratio, "White Rook", PieceData.wr, "h1"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Rook", PieceData.br, "a8"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Rook", PieceData.br, "h8"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "a2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "b2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "c2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "d2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "e2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "f2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "g2"));
- components.add(new Piece(b.ctx, b.ratio, "White Pawn", PieceData.wp, "h2"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "a7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "b7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "c7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "d7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "e7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "f7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "g7"));
- components.add(new Piece(b.ctx, b.ratio, "Black Pawn", PieceData.bp, "h7"));
-
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "a2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "b2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "c2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "d2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "e2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "f2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "g2"));
+ pieces.add(new Piece(_ctx, _ratio, "White Pawn", PieceData.wp, "h2"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "a7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "b7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "c7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "d7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "e7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "f7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "g7"));
+ pieces.add(new Piece(_ctx, _ratio, "Black Pawn", PieceData.bp, "h7"));
+
+ board.pieces = pieces;
+
canvas.on.mouseDown.add((MouseEvent e) {
- b.select(e.offsetX, e.offsetY);
+ board.selectSquare(e.offsetX, e.offsetY);
});
- canvas.on.touchStart.add((TouchEvent t) {
- if (t.touches.length == 1) {
- b.select(t.touches[0].clientX, t.touches[0].clientY);
- }
- });
+ }
+
+
+ draw() {
+ board.draw();
+ pieces.forEach((p)=>p.draw());
+ }
- anim(int t) {
- components.forEach((c) => c.draw());
+ anim(int i) {
+ draw();
window.requestAnimationFrame(anim);
- };
+ }
+}
+
+void main() {
+ CanvasElement canvas = query("#board");
+ ChessEngine.Engine engine = new ChessEngine.Engine();
+ Game game = new Game(canvas, engine);
+ window.requestAnimationFrame(game.anim);
- window.requestAnimationFrame(anim);
+
+//
+// print("setting piece selection");
+//
+// List<List<int>> moves = engine.GetValidMoves(boardsquare.col, boardsquare.row);
+//
+// if (moves != null) {
+// if (moves.length != 0) {
+// engine.SetChessPieceSelection(boardsquare.col, boardsquare.row, true);
+// }
+//
+// moves.forEach((sq) {
+// b.highlight(sq[0], sq[1]);
+// });
+// }
+// };
+//
+//
+
}
View
2 samples/canvasclient/canvasclient/canvasclient.html
@@ -9,6 +9,6 @@
<body>
<canvas id="board" height="400" width="400" />
<script type="application/dart" src="canvasclient.dart"></script>
- <script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
+ <script src="dart.js"></script>
</body>
</html>
View
236 samples/canvasclient/canvasclient/dart.js
@@ -0,0 +1,236 @@
+// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Bootstrap support for Dart scripts on the page as this script.
+if (navigator.webkitStartDart) {
+ if (!navigator.webkitStartDart()) {
+ document.body.innerHTML = 'This build has expired. Please download a new Dartium at http://www.dartlang.org/dartium/index.html';
+ }
+} else {
+ // TODO:
+ // - Support in-browser compilation.
+ // - Handle inline Dart scripts.
+ window.addEventListener("DOMContentLoaded", function (e) {
+ // Fall back to compiled JS. Run through all the scripts and
+ // replace them if they have a type that indicate that they source
+ // in Dart code.
+ //
+ // <script type="application/dart" src="..."></script>
+ //
+ var scripts = document.getElementsByTagName("script");
+ var length = scripts.length;
+ for (var i = 0; i < length; ++i) {
+ if (scripts[i].type == "application/dart") {
+ // Remap foo.dart to foo.dart.js.
+ if (scripts[i].src && scripts[i].src != '') {
+ var script = document.createElement('script');
+ script.src = scripts[i].src + '.js';
+ var parent = scripts[i].parentNode;
+ parent.replaceChild(script, scripts[i]);
+ }
+ }
+ }
+ }, false);
+}
+
+// ---------------------------------------------------------------------------
+// Experimental support for JS interoperability
+// ---------------------------------------------------------------------------
+function SendPortSync() {
+}
+
+function ReceivePortSync() {
+ this.id = ReceivePortSync.id++;
+ ReceivePortSync.map[this.id] = this;
+}
+
+(function() {
+ function serialize(message) {
+ var visited = [];
+ function checkedSerialization(obj, serializer) {
+ // Implementation detail: for now use linear search.
+ // Another option is expando, but it may prohibit
+ // VM optimizations (like putting object into slow mode
+ // on property deletion.)
+ var id = visited.indexOf(obj);
+ if (id != -1) return [ 'ref', id ];
+ var id = visited.length;
+ visited.push(obj);
+ return serializer(id);
+ }
+
+ function doSerialize(message) {
+ if (message == null) {
+ return null; // Convert undefined to null.
+ } else if (typeof(message) == 'string' ||
+ typeof(message) == 'number' ||
+ typeof(message) == 'boolean') {
+ return message;
+ } else if (message instanceof Array) {
+ return checkedSerialization(message, function(id) {
+ var values = new Array(message.length);
+ for (var i = 0; i < message.length; i++) {
+ values[i] = doSerialize(message[i]);
+ }
+ return [ 'list', id, values ];
+ });
+ } else if (message instanceof LocalSendPortSync) {
+ return [ 'sendport', 'nativejs', message.receivePort.id ];
+ } else if (message instanceof DartSendPortSync) {
+ return [ 'sendport', 'dart', message.isolateId, message.portId ];
+ } else {
+ return checkedSerialization(message, function(id) {
+ var keys = Object.getOwnPropertyNames(message);
+ var values = new Array(keys.length);
+ for (var i = 0; i < keys.length; i++) {
+ values[i] = doSerialize(message[keys[i]]);
+ }
+ return [ 'map', id, keys, values ];
+ });
+ }
+ }
+ return doSerialize(message);
+ }
+
+ function deserialize(message) {
+ return deserializeHelper(message);
+ }
+
+ function deserializeHelper(x) {
+ if (x == null ||
+ typeof(x) == 'string' ||
+ typeof(x) == 'number' ||
+ typeof(x) == 'boolean') {
+ return x;
+ }
+ switch (x[0]) {
+ case 'map': return deserializeMap(x);
+ case 'sendport': return deserializeSendPort(x);
+ case 'list': return deserializeList(x);
+ default: throw 'unimplemented';
+ }
+ }
+
+ function deserializeMap(x) {
+ var result = { };
+ var id = x[1];
+ var keys = x[2];
+ var values = x[3];
+ for (var i = 0, length = keys.length; i < length; i++) {
+ var key = deserializeHelper(keys[i]);
+ var value = deserializeHelper(values[i]);
+ result[key] = value;
+ }
+ return result;
+ }
+
+ function deserializeSendPort(x) {
+ var tag = x[1];
+ switch (tag) {
+ case 'nativejs':
+ var id = x[2];
+ return new LocalSendPortSync(ReceivePortSync.map[id]);
+ case 'dart':
+ var isolateId = x[2];
+ var portId = x[3];
+ return new DartSendPortSync(isolateId, portId);
+ default:
+ throw 'Illegal SendPortSync type: $tag';
+ }
+ }
+
+ function deserializeList(x) {
+ var values = x[2];
+ var length = values.length;
+ var result = new Array(length);
+ for (var i = 0; i < length; i++) {
+ result[i] = deserializeHelper(values[i]);
+ }
+ return result;
+ }
+
+ window.registerPort = function(name, port) {
+ var stringified = JSON.stringify(serialize(port));
+ window.localStorage['dart-port:' + name] = stringified;
+ };
+
+ window.lookupPort = function(name) {
+ var stringified = window.localStorage['dart-port:' + name];
+ return deserialize(JSON.parse(stringified));
+ };
+
+ ReceivePortSync.id = 0;
+ ReceivePortSync.map = {};
+
+ ReceivePortSync.dispatchCall = function(id, message) {
+ // TODO(vsm): Handle and propagate exceptions.
+ var deserialized = deserialize(message);
+ var result = ReceivePortSync.map[id].callback(deserialized);
+ return serialize(result);
+ };
+
+ ReceivePortSync.prototype.receive = function(callback) {
+ this.callback = callback;
+ };
+
+ ReceivePortSync.prototype.toSendPort = function() {
+ return new LocalSendPortSync(this);
+ };
+
+ ReceivePortSync.prototype.close = function() {
+ delete ReceivePortSync.map[this.id];
+ };
+
+ if (navigator.webkitStartDart) {
+ window.addEventListener('js-sync-message', function(event) {
+ var data = JSON.parse(event.data);
+ var deserialized = deserialize(data.message);
+ var result = ReceivePortSync.map[data.id].callback(deserialized);
+ // TODO(vsm): Handle and propagate exceptions.
+ dispatchEvent('js-result', serialize(result));
+ }, false);
+ }
+
+ function LocalSendPortSync(receivePort) {
+ this.receivePort = receivePort;
+ }
+
+ LocalSendPortSync.prototype = new SendPortSync();
+
+ LocalSendPortSync.prototype.callSync = function(message) {
+ // TODO(vsm): Do a direct deepcopy.
+ message = deserialize(serialize(message));
+ return this.receivePort.callback(message);
+ }
+
+ function DartSendPortSync(isolateId, portId) {
+ this.isolateId = isolateId;
+ this.portId = portId;
+ }
+
+ DartSendPortSync.prototype = new SendPortSync();
+
+ function dispatchEvent(receiver, message) {
+ var string = JSON.stringify(message);
+ var event = document.createEvent('TextEvent');
+ event.initTextEvent(receiver, false, false, window, string);
+ window.dispatchEvent(event);
+ }
+
+ DartSendPortSync.prototype.callSync = function(message) {
+ var serialized = serialize(message);
+ var target = 'dart-port-' + this.isolateId + '-' + this.portId;
+ // TODO(vsm): Make this re-entrant.
+ // TODO(vsm): Set this up set once, on the first call.
+ var source = target + '-result';
+ var result = null;
+ var listener = function (e) {
+ result = JSON.parse(e.data);
+ };
+ window.addEventListener(source, listener, false);
+ dispatchEvent(target, [source, serialized]);
+ window.removeEventListener(source, listener, false);
+ return deserialize(result);
+ }
+})();
View
2 samples/canvasclient/canvasclient/utils.dart
@@ -16,7 +16,7 @@ class Utils {
return _row;
}
- static toSquare(_col, _row) {
+ static String toSquare(_col, _row) {
if (_row < 1 || _row > 8 || _col < 1 || _col > 8) {
return null;
}
View
6 samples/canvasclient/tests/TestBoard/TestBoard.dart
@@ -11,15 +11,15 @@ void main() {
CanvasElement canvas = query("#board");
CanvasRenderingContext2D ctx = canvas.getContext("2d");
- Board board = new Board(ctx, height: canvas.height, width: canvas.width);
+ Board board = new Board(ctx, null, height: canvas.height, width: canvas.width);
canvas.on.mouseDown.add((MouseEvent e) {
- board.select(e.offsetX, e.offsetY);
+ board.selectSquare(e.offsetX, e.offsetY);
});
canvas.on.touchStart.add((TouchEvent t) {
if (t.touches.length == 1) {
- board.select(t.touches[0].clientX, t.touches[0].clientY);
+ board.selectSquare(t.touches[0].clientX, t.touches[0].clientY);
}
});

0 comments on commit d051953

Please sign in to comment.