-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconnect-four.js
More file actions
95 lines (89 loc) · 2.47 KB
/
Copy pathconnect-four.js
File metadata and controls
95 lines (89 loc) · 2.47 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
function Game(p1, p2, handleWin, handleDrop) {
this.currentPlayer = p1;
this.waitingPlayer = p2;
this.inProgress = true;
this.handleWin = handleWin;
this.handleDrop = handleDrop;
this.board = [];
for(var i = 0; i < 7; i++) {
this.board[i] = [];
for(var j = 0; j < 6; j++) {
this.board[i][j] = 0;
}
}
this.dropCell = function(col) {
for(var row = 5; row >= 0; row--) {
if(this.board[col][row] == 0) {
this.board[col][row] = this.currentPlayer;
var temp = this.currentPlayer;
this.currentPlayer = this.waitingPlayer;
this.waitingPlayer = temp;
break;
} else if(this.board[col][row] != 0 && row == 0) {
throw "FullColError";
}
}
this.handleDrop(col);
this.checkForWinner();
}
this.checkWinnerFrom = function(col, row) {
var player = this.board[col][row];
for(var i = col - 1; i <= col + 1; i++) {
for(var j = row - 1; j <= row + 1; j++) {
if(i < 0 || j < 0 || i > 6 || j > 5 || (i == col && j == row)) continue;
if(this.board[i][j] == player) {
if(this.checkWinnerInDirection(col, row, i - col, j - row)) {
return true;
}
}
}
}
}
this.checkWinnerInDirection = function(col, row, left, up) {
var player = this.board[col][row];
for(var i = 0; i <= 3; i ++) {
var x = col + left*i;
var y = row + up*i;
if(x < 0 || y < 0 || x > 6 || y > 5) return false;
if(this.board[x][y] == player) continue;
else { return false; }
}
return true;
}
// Returns false if no one has won
this.checkForWinner = function() {
var empty = false;
for(var col = 0; col < 7; col++) {
for(var row = 0; row < 6; row++) {
if(this.board[col][row] == 0) {
empty = true;
continue;
} else if(this.checkWinnerFrom(col, row)) {
this.inProgress = false;
this.handleWin(this.board[col][row]);
return;
}
}
}
if(!empty) {
this.inProgress = false;
// 0 means tie
this.handleWin(0);
}
}
this.potentialRow = function(col) {
for(var row = 5; row >= 0; row--) {
if(this.board[col][row] == 0) {
return row;
break;
} else if(this.board[col][row] != 0 && row == 0) {
return undefined;
}
}
}
}
if(typeof exports != "undefined") {
exports.createGame = function(p1, p2, onWin, onDrop) {
return new Game(p1, p2, onWin, onDrop);
}
}