-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
107 lines (105 loc) · 2.43 KB
/
script.js
File metadata and controls
107 lines (105 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
function fetchBoard() {
var board;
board = ["", "", "", "", "", "", "", "", ""];
$("#tictac td").each(function (index) {
board[index] = $(this).text();
});
return board;
}
function checkRow(a, b, c) {
if (a === "X" && b === "X" && c === "X") {
return 1;
} else if (a === "O" && b === "O" && c === "O") {
return -1;
} else {
return 0;
}
}
function checkWin(board) {
return (
checkRow(board[0], board[1], board[2]) +
checkRow(board[3], board[4], board[5]) +
checkRow(board[6], board[7], board[8]) +
checkRow(board[0], board[3], board[6]) +
checkRow(board[1], board[4], board[7]) +
checkRow(board[2], board[5], board[8]) +
checkRow(board[0], board[4], board[8]) +
checkRow(board[2], board[4], board[6])
);
}
function selectMove(board) {
var i, options;
options = [];
for (i = 0; i < 9; i += 1) {
if (board[i] === "") {
options.push(i);
}
}
if (options.length === 0) {
return -1;
} else {
return options[Math.floor(Math.random() * options.length)];
}
}
function showGameOver(result) {
var target;
target = $("#result");
if (result > 0) {
target.text("X win!");
} else if (result < 0) {
target.text("O win!");
} else {
target.text("Draw");
}
}
$(document).ready(function () {
var ordi = "O";
var ordiVal = "O";
var player = "X";
$(".playerPick").click(function () {
player = $(this).val();
ordi = "";
if (player == "X") {
ordi = "O";
ordiVal = "O";
$("#tictac td").text("");
} else {
ordi = "X";
ordiVal = "X";
$("#tictac td").text("");
}
$("#result").text("You are currently playing as " + player);
});
$("#tictac td").click(function () {
var xCell, board, result, oLocation, oCell;
xCell = $(this);
if (xCell.text() !== "" || checkWin(fetchBoard()) !== 0) {
return;
}
xCell.text(player);
board = fetchBoard();
result = checkWin(board);
if (result !== 0) {
showGameOver(result);
return;
}
ordi = selectMove(board);
if (ordi < 0) {
showGameOver(0);
return;
}
board[ordi] = ordi;
oCell = $("#cell" + ordi);
oCell.text(ordiVal);
board = fetchBoard();
result = checkWin(board);
if (result !== 0) {
showGameOver(result);
return;
}
});
$("#reset").click(function () {
$("#tictac td").text("");
$("#result").text("You are currently playing as " + player);
});
});