Skip to content

Instantly share code, notes, and snippets.

@HBehrens
Created November 9, 2013 17:52
Show Gist options
  • Save HBehrens/7387971 to your computer and use it in GitHub Desktop.
Save HBehrens/7387971 to your computer and use it in GitHub Desktop.
tr {
height: 42px;
}
td {
width: 40px;
font-size: 32px;
border: 1px solid black;
text-align: center;
vertical-align: middle;
cursor: pointer;
}
<html ng-app="App">
<head>
<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
</head>
<body>
<h4 id="source_tic-tac-toe">Tic-Tac-Toe</h4>
<div ng-controller="TicTacToeCntl">
Next Player: {{nextMove}}
<div class="winner" ng-show="winner">Player {{winner}} has won!</div>
<table class="board">
<tr ng-repeat="row in board track by $index">
<td ng-repeat="cell in row track by $index"
ng-click="dropPiece($parent.$index, $index)">{{cell}}</td>
</tr>
</table>
<button ng-click="reset()">reset board</button>
</div>
</body>
</html>
angular.module('App', []);
function TicTacToeCntl($scope) {
$scope.reset = function() {
$scope.board = [
['', '', ''],
['', '', ''],
['', '', '']
];
$scope.nextMove = 'X';
$scope.winner = '';
$scope.grade();
};
$scope.dropPiece = function(row, col) {
if (!$scope.winner && !$scope.board[row][col]) {
$scope.board[row][col] = $scope.nextMove;
$scope.nextMove = $scope.nextMove == 'X' ? 'O' : 'X';
$scope.grade();
}
};
$scope.grade = function() {
var b = $scope.board;
function same(a, b, c) { return (a==b && b==c) ? a : '';}
function row(r) { return same(b[r][0], b[r][1], b[r][2]);}
function col(c) { return same(b[0][c], b[1][c], b[2][c]);}
function diagonal(i) { return same(b[0][1-i], b[1][1], b[2][1+i]);}
$scope.winner =
row(0) || row(1) || row(2) ||
col(0) || col(1) || col(2) ||
diagonal(-1) || diagonal(1);
};
$scope.reset();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment