-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
113 lines (105 loc) · 2.94 KB
/
scripts.js
File metadata and controls
113 lines (105 loc) · 2.94 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
106
107
108
109
110
111
112
113
let grid = [];
colors = ["#0051ba", "#e8000d"]; //KU Blue/Crimson
teams = ["blue", "red"]
window.addEventListener("DOMContentLoaded", ()=>{
let turn = 0;
for(let i = 0; i < 7; i++){
grid.push([]);
for(let j = 0; j < 6; j++){
grid[i].push("-"); //Fill empty grid
}
}
for(let i = 0; i < 6; i++){
for(let j = 0; j < 7; j++){
document.body.innerHTML += "<div class=\"square\" id = \"" + j + i + "\"></div>"; //Fill DOM with squares
}
document.body.innerHTML += "<br>";
}
for(let i = 0; i < 7; i++){
document.body.innerHTML += "<button type=\"button\" id =\"" + i + "\">"; //Add the buttons
}
document.body.innerHTML += "<p id=\"turn\">Turn 1: blue</p>";
document.addEventListener("click", (e)=>{
if(e.target.type == "button" && e.target.id != "computer"){
if(drop((turn)%2,parseInt(e.target.id),grid,0)){
turn++;
document.getElementById("turn").innerText = "Turn " + turn + ": " + teams[(turn) % 2];
if(checkWin("0",grid)){
alert("Blue Wins! Red is bad.");
location.reload();
}
if(checkWin("1",grid)){
alert("Red Wins! Blue is bad.");
location.reload();
}
}
}
})
})
function drop(symbol, slot, board, isComp){
if(board[slot][5] != "-"){
return(0) //if the top of the column is full
}
else{
let cur = 5;
while(board[slot][cur-1] == "-" && cur > 0){
cur--; //Move down the column and then fill in the grid and the html squares
}
board[slot][cur] = symbol;
cur = 5-cur;
if(!isComp){
document.getElementById(slot + "" + cur).style.backgroundColor = colors[symbol];
}
return(1);
}
}
function checkWin(symbol, board){
for(let row = 0; row < 6; row++){
for(let col = 0; col < 7; col++){
let j = col;
let i = row;
if(board[j][i] == symbol){
let cur = 1;
while(j + 1 < 7 && board[j+1][i] == symbol){
cur += 1;
if(cur == 4){
return(true); //4 in a row on the same row.
}
j += 1;
}
cur = 1
j = col
i = row
while(i + 1 < 6 && board[j][i+1] == symbol){
cur += 1
if(cur == 4){
return(true);//4 in a row on the same column
}
i += 1;
}
cur = 1;
j = col;
i = row;
while(i + 1 < 6 && j + 1 < 7 && board[j+1][i+1] == symbol){
cur += 1;
if(cur == 4){
return(true); //4 in a row, upper right.
}
i += 1;
j += 1;
}
cur = 1;
j = col;
i = row;
while(i + 1 < 6 && j - 1 > 0 && board[j-1][i+1] == symbol){
cur += 1;
if(cur == 4){
return(true); // 4 in a row upper left
}
i += 1;
j -= 1;
}
}
}
}
}