/
tictactoe.js
86 lines (70 loc) · 1.88 KB
/
tictactoe.js
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
function TicTacToeGame() {
this.VALID_FIELD_IDS = new Array('TL', 'TC', 'TR', 'CL', 'CC', 'CR', 'BL', 'BC', 'BR');
this.state = new Array();
this.moveCount = 0;
}
TicTacToeGame.prototype = {
}
TicTacToeGame.prototype.reset = function() {
this.state = new Array();
this.moveCount = 0;
};
TicTacToeGame.prototype.getActivePlayer = function() {
if(this.moveCount % 2 == 0)
return 'Player One';
else
return 'Player Two';
};
TicTacToeGame.prototype.makeMoveTo = function(fieldId) {
if(!this.canSetTo(fieldId)) {
alert('This field is already taken.');
return;
}
var marker = this.getCurrentMarker();
this.state[fieldId] = marker;
this.moveCount++;
};
TicTacToeGame.prototype.canSetTo = function(fieldId) {
console.log(this.state);
console.log(this.moveCount);
var fieldIsTaken = this.state[fieldId];
return !fieldIsTaken;
};
TicTacToeGame.prototype.getCurrentMarker = function() {
if(this.moveCount % 2 == 0)
return 'X';
else
return 'O';
};
TicTacToeGame.prototype.getFieldTextAt = function(fieldId) {
// return this.state[fieldId];
// The line below will fix the newGame error :)
// Can you explain why?
return this.state[fieldId] || " ";
};
TicTacToeGame.prototype.getValidFieldIds = function() {
return this.VALID_FIELD_IDS;
};
var game = new TicTacToeGame();
function handleFieldClick(fieldId) {
game.makeMoveTo(fieldId);
updateActivePlayer();
updateGameBoard();
}
function newGame() {
// this is currently not working.
// Changing the method game.getFieldTextAt will fix this ...
game.reset();
updateActivePlayer();
updateGameBoard();
}
function updateActivePlayer() {
$('#playerName').html(game.getActivePlayer());
}
function updateGameBoard() {
for (var i = 0; i < game.getValidFieldIds().length; i++) {
var fieldId = game.getValidFieldIds()[i];
var field = $("#field_" + fieldId + " .ui-btn-text");
field.html(game.getFieldTextAt(fieldId));
}
}