Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

141 lines (127 sloc) 2.947 kb
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Existential Crisis: Tic-Tac-Toe</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Copyright 2012 Brett Slatkin -->
<style type="text/css">
table td {
width: 200px;
height: 200px;
border: 1px solid #000;
text-align: center;
font-size: 108px;
vertical-align: middle;
}
table {
border-collapse: collapse;
}
.play-X {
color: #000;
}
.play-O {
color: #f00;
}
</style>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<table>
<tr>
<td data-row="0" data-column="0">&nbsp;</td>
<td data-row="0" data-column="1">&nbsp;</td>
<td data-row="0" data-column="2">&nbsp;</td>
</tr>
<tr>
<td data-row="1" data-column="0">&nbsp;</td>
<td data-row="1" data-column="1">&nbsp;</td>
<td data-row="1" data-column="2">&nbsp;</td>
</tr>
<tr>
<td data-row="2" data-column="0">&nbsp;</td>
<td data-row="2" data-column="1">&nbsp;</td>
<td data-row="2" data-column="2">&nbsp;</td>
</tr>
</table>
<script type="text/javascript">
var WINNER = false;
var BOARD = [
['', '', ''], // [column 0, column 1, column 2]
['', '', ''],
['', '', '']
];
var COLOR = 'X';
$('td').click(function(e) {
if (WINNER) {
return;
}
// Mark the move, if legal.
var target = $(e.target);
var column = parseInt(target.data('column'));
var row = parseInt(target.data('row'));
if (!BOARD[row][column]) {
BOARD[row][column] = COLOR;
} else {
alert('Illegal move!');
return;
}
// Toggle who's playing.
if (COLOR == 'X') {
COLOR = 'O';
} else {
COLOR = 'X';
}
// Update board state.
$('td').each(function() {
var cell = $(e.target);
var column = parseInt(cell.data('column'));
var row = parseInt(cell.data('row'));
if (BOARD[row][column]) {
cell.text(BOARD[row][column]);
cell.addClass('play-' + BOARD[row][column]);
} else {
cell.html('&nbsp;');
cell.attr('class', '');
}
});
// Check for a winner.
// Horizontal
for (var i = 0; i < 3; i++) {
if (BOARD[i][0] &&
BOARD[i][0] == BOARD[i][1] &&
BOARD[i][1] == BOARD[i][2]) {
alert(BOARD[i][0] + ' has won!');
WINNER = true;
return;
}
}
// Vertical
for (var i = 0; i < 3; i++) {
if (BOARD[0][i] &&
BOARD[0][i] == BOARD[1][i] &&
BOARD[1][i] == BOARD[2][i]) {
alert(BOARD[0][i] + ' has won!');
WINNER = true;
return;
}
}
// Diagnol
if (BOARD[0][0] &&
BOARD[0][0] == BOARD[1][1] &&
BOARD[1][1] == BOARD[2][2]) {
alert(BOARD[0][0] + ' has won!');
WINNER = true;
return;
}
if (BOARD[0][2] &&
BOARD[0][2] == BOARD[1][1] &&
BOARD[1][1] == BOARD[2][0]) {
alert(BOARD[0][2] + ' has won!');
WINNER = true;
return;
}
});
</script>
</body>
</html>
Jump to Line
Something went wrong with that request. Please try again.