From 63df6b0b52d5f7b3e2885009c6fdf5f29288e227 Mon Sep 17 00:00:00 2001 From: Wanja Date: Fri, 23 Mar 2012 01:35:02 +0100 Subject: [PATCH] First (untested) version of tafl.js --- assets/www/tafl.js | 201 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 assets/www/tafl.js diff --git a/assets/www/tafl.js b/assets/www/tafl.js new file mode 100644 index 0000000..07fa8cb --- /dev/null +++ b/assets/www/tafl.js @@ -0,0 +1,201 @@ +/* + * This is the JS Tafl Game lib and part of Androtafl. + */ + +(function () { + 'use strict'; + + Array.prototype.has = function(obj) { + var i = this.length; + while (i--) { + if (this[i] === obj) { + return true; + } + } + return false; + }; + + function TaflState() { + this.board = ['']; + this.N = 0; + this.to_move = 'w'; + this.legal_moves_cache = null; + this.winner = null; + + this.loadBoard = function(board) { + this.board = board; + this.N = board.length; + if (board[0].length !== this.N) throw "BoardNotSquare"; + }; + + this.clone = function() { + var i, t = new TaflState(); + + for (i = 0; i < this.N; ++i) { + t.board[i] = this.board[i]; + } + + t.N = this.N; + t.to_move = this.to_move; + t.legal_moves_cache = this.legal_moves_cache; + t.winner = this.winner; + } + } + + var Tafl = { + legal_moves: function(s) { + if (s.legal_moves_cache) return s.legal_moves_cache; + + var i,j,k, N=s.N, moves=[], legal_fields; + + + for (i=0; i 0 && j > 0 && i < s.N-1 && j < s.N-1) { // King is in not on + // an edge + if (king_capturers.has(s.board[i][j-1]) && king_capturers.has(s.board[i][j+1]) && + king_capturers.has(s.board[i-1][j]) && king_capturers.has(s.board[i+1][j])) { + catches.push([i,j]); + } + } + + + return catches; + }, + + is_moving_color: function(s, move) { + var i=move[0], j=move[1]; + + if (s.to_move === s.board[i][j]) return true; + // K and k are both kings + if (s.to_move === 'B' && s.board[i][j].toUpperCase() === 'K') return true; + + return false; + }, + + find_king: function(s) { + for (i=0; i 0) s.board[i].find('k'); // King is on throne? + if (j >= 0) return [i,j]; + } + + return null; + } + + terminal_test: function(s) { + var i, j, king_found = false, corners; + + // find position of king and check if he's on an edge + for (i=0; i 0) s.board[i].find('k'); // King is on throne? + + if (j >= 0) { // Found king + + // King is at an edge + if (i === 0 || i === s.N-1 || j === 0 || j === s.N-1) { + s.winner = 'B'; + return true; + } + + kind_found = true; + break; + } + } + + if (! king_found) { + s.winner = 'W'; + return true; // King was captured + } + + // Are there any legal moves? If not, player loses + if (this.legal_moves(s).length == 0) { + if (s.to_move === 'W') s.winner = 'B'; + else s.winner = 'W'; + return true; + } + + return false; // no one won, yet + } + }; +})();