Tic Tac Toe with Synchroscope + AngularJS
Just a simple Synchroscope and AngularJS app!
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/2.0.8/es5-shim.min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
<script src="http://synchroscope.herokuapp.com/sync.js"></script>
<script src="http://synchroscope.herokuapp.com/socket.io/socket.io.js"></script>
<div ng-app="tictactoe" ng-controller="Game">
<p>You are:
<label>
<input type="radio" value="O" ng-model="player" /><strong>O</strong>
</label>
<label>
<input type="radio" value="X" ng-model="player" value="Clear Board" /><strong>X</strong>
</label>
</p>
<div ng-show="$ynchronized">
<h2 ng-show="currentPlayer == player">Your Turn</h2>
<h2 ng-show="currentPlayer != player">Waiting for Opponent</h2>
<h2 ng-show="winner">WINNER IS {{winner}}!! <input type="button" ng-click="newGame()" value="New Game" /></h2>
<table border="1">
<tr ng-repeat="row in [0,1,2]">
<td ng-repeat="column in [0,1,2]" ng-click="cellClick(row,column)" ng-class="cellClass(row,column)">{{cellText(row,column)}}</td>
</tr>
</table>
</div>
<div ng-hide="$ynchronized">
<h2>Synchronizing with Server</h2>
</div>
</div>
SCSS
.cell {
width: 100px;
height: 100px;
font: 90px sans-serif;
text-align: center;
vertical-align: center;
}
JavaScript
var tic = angular.module('tictactoe', ['synchroscope'])
tic.controller('Game', function ($scope, $ync) {
// == initialize scope ==
$scope.currentPlayer = 'O'
$scope.player = 'O'
$scope.winner = null
$scope.board = [
[null, null, null],
[null, null, null],
[null, null, null]
]
// == sync scope variables ==
var keys = ['board', 'currentPlayer', 'winner']
$ync($scope, keys, 'http://synchroscope.herokuapp.com/synchroscope#tictactoe')
// == scope functions ==
$scope.cellClass = function (row, column) {
var value = cell(row, column)
return 'cell cell-' + value
}
$scope.cellText = function (row, column) {
var value = cell(row, column)
return value ? value : '-'
}
$scope.cellClick = function (row, column) {
if ($scope.winner) {
alert('Already game over.')
return
}
if ($scope.player != $scope.currentPlayer) {
alert('Not your turn.')
return
}
setCell(row, column, $scope.player)
checkBoard()
$scope.currentPlayer = nextPlayer($scope.currentPlayer)
}
$scope.newGame = function () {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
setCell(i, j, null)
}
}
$scope.currentPlayer = 'O'
$scope.player = 'O'
$scope.winner = null
}
// == utility functions ==
// returns the value of cell
function cell(row, column) {
return $scope.board[row][column]
}
// sets the value of cell
function setCell(row, column, value) {
$scope.board[row][column] = value
}
// returns the next player
function nextPlayer(player) {
return {
O: 'X',
X: 'O'
}[player]
}
// checks the board and declare winner
function checkBoard() {
var winner, empty = false
// check...