-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkforwin.js
114 lines (97 loc) · 2.5 KB
/
checkforwin.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Exporting the checkForWin function.
module.exports = {
checkForWin: checkForWin
}
function checkForWin(boardstate){
var result = 0;
var success = false;
for(var i = 0; i < 7 && !success; i++){
for(var j = 0; j < boardstate[i].length && !success; j++){
result = checkAtSpot(boardstate, i, j, boardstate[i][j]);
if(result){
success = true;
console.log("Player", result, "has won the game.");
}
}
}
return result;
}
// Helper Functions
function checkAtSpot(boardstate, loci, locj, occupy){
if(!occupy)
return 0;
else{
var victor = 0;
victor = checkHorizontal(boardstate, 1, occupy, loci, locj);
if(victor)
return victor;
victor = checkVertical(boardstate, 1, occupy, loci, locj);
if(victor)
return victor;
victor = checkDiagPos(boardstate, 1, occupy, loci, locj);
if(victor)
return victor;
victor = checkDiagNeg(boardstate, 1, occupy, loci, locj);
return victor;
}
}
function checkHorizontal(boardstate, prev, playerOfInterest, loci, locj){
loci++;
if(loci > 6 || boardstate[loci].length <= locj)
return 0;
if(boardstate[loci][locj] == playerOfInterest){
prev++;
if(prev == 4)
return playerOfInterest;
else
return checkHorizontal(boardstate, prev, playerOfInterest, loci, locj);
}
else
return 0;
}
function checkVertical(boardstate, prev, playerOfInterest, loci, locj){
locj++;
if(locj > 5 || boardstate[loci].length <= locj)
return 0;
if(boardstate[loci][locj] == playerOfInterest){
prev++;
if(prev == 4){
console.log("Player ", playerOfInterest, " returned!");
return playerOfInterest;
}
else
return checkVertical(boardstate, prev, playerOfInterest, loci, locj);
}
else
return 0;
}
function checkDiagPos(boardstate, prev, playerOfInterest, loci, locj){
loci++;
locj++;
if(locj > 5 || loci > 6 || boardstate[loci].length <= locj)
return 0;
if(boardstate[loci][locj] == playerOfInterest){
prev++;
if(prev == 4)
return playerOfInterest;
else
return checkDiagPos(boardstate, prev, playerOfInterest, loci, locj);
}
else
return 0;
}
function checkDiagNeg(boardstate, prev, playerOfInterest, loci, locj){
loci++;
locj--;
if(locj < 0 || loci > 6 || boardstate[loci].length <= locj)
return 0;
if(boardstate[loci][locj] == playerOfInterest){
prev++;
if(prev == 4)
return playerOfInterest;
else
return checkDiagNeg(boardstate, prev, playerOfInterest, loci, locj);
}
else
return 0;
}