-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
494 lines (427 loc) · 12 KB
/
index.html
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous"
/>
<script src="d3.v3.min.js"></script>
<style>
circle.node {
fill: white;
stroke: black;
}
circle.node + text {
text-anchor: middle;
}
text {
font-family: sans-serif;
pointer-events: none;
}
.btn-dark:hover {
background-color: rgb(217, 217, 98) !important;
color: #343a40;
}
</style>
<title>CoinStack!</title>
</head>
<body>
<div class="container">
<div id="heading">
<h1 class="text-center">The game of Coin Stack</h1>
<hr />
</div>
<div class="text-center" id="info-wrapper">
<div class="alert alert-warning" id="info-text">
Waiting for play...
</div>
</div>
<div id="form">
<div class="form-row">
<div class="form-group col-4">
<label for="#coins-choice"
>Choose number of coins</label
>
<input
type="number"
name="coins-choice"
id="coins-choice"
class="form-control"
value="10"
required
/>
</div>
<div class="form-group col-4">
<label for="diff-choice">Select difficulty</label>
<select class="form-control" id="diff-choice">
<option value="easy">Easy</option>
<option value="hard">HARD</option>
</select>
</div>
<div class="form-group col-4">
<label for="turn-choice"
>Select to go first or second</label
>
<select class="form-control" id="turn-choice">
<option value="first">Go first</option>
<option value="second">Go second</option>
</select>
</div>
</div>
<div class="form-group">
<button
id="start-game"
class="btn btn-success"
type="button"
>
Start game!
</button>
</div>
</div>
<hr class="my-4" />
<div id="coins-wrapper" class="row">
<div id="coins" class="btn-group-vertical col"></div>
<div id="network-analysis" class="col"></div>
</div>
</div>
</body>
<script>
"use strict";
let READY_ALERT_STYLE = "alert alert-warning";
let PLAYER_TURN_ALERT_STYLE = "alert alert-primary";
let CPU_TURN_ALERT_STYLE = "alert alert-info";
let LOSS_ALERT_STYLE = "alert alert-danger";
let WIN_ALERT_STYLE = "alert alert-success";
let START_BTN_STYLE = "btn btn-success";
let RESET_BTN_STYLE = "btn btn-warning";
let COIN_BTN_STYLE = "btn btn-dark";
// REFACTOR: remove global vars; make class structure
let btns = [];
let nodes, links, lines, gnodes, circles, labels;
let infoText = document.querySelector("#info-text");
let startBtn = document.querySelector("#start-game");
let btnGroup = document.querySelector("#coins");
let coinsChoiceEl = document.querySelector("#coins-choice");
let turnChoiceEl = document.querySelector("#turn-choice");
let difficultyChoiceEl = document.querySelector("#diff-choice");
let networkEl = document.querySelector("#network-analysis");
function mex(values) {
let min = 0;
while (values.includes(min)) {
min++;
}
return min;
}
function removeCircleHighlight() {
for (let n = 0; n < circles[0].length; n++) {
circles[0][n].style.stroke = "black";
circles[0][n].style.strokeWidth = 1;
}
}
function highlightCircle(index, isPlayerTurn) {
// highlight current number of coins on graph
let color = isPlayerTurn ? "red" : "blue";
circles[0][index].style.stroke = color;
circles[0][index].style.strokeWidth = 5;
// highlight optimal strategy for player
if (isPlayerTurn) {
let targetedNodes = links
.filter((link) => link.source.id === index)
.map((link) => link.target);
let idealMoves = targetedNodes.filter((node) => node.gs === 0);
if (idealMoves.length > 0) {
let firstIdeal = idealMoves[0].id;
// highlight the one whose gs val is 0
circles[0][firstIdeal].style.stroke = "green";
circles[0][firstIdeal].style.strokeWidth = 5;
} else {
// TODO:
// If easy mode
// choose node where next gsVal != 0
// if hard
// welp
}
}
}
function addStartListener() {
startBtn.addEventListener("click", startGame);
}
function addButtonListeners(isPlayerTurn, round, isHard) {
infoText.classList = PLAYER_TURN_ALERT_STYLE;
infoText.innerHTML = "Choose one or two of the top coins to remove";
btns[0].addEventListener("click", (e) => {
e.currentTarget.remove();
removeCircleHighlight();
btns.splice(0, 1);
round += 1;
isPlayerTurn = !isPlayerTurn;
nextRound(isPlayerTurn, round, isHard);
});
btns[1].addEventListener("click", (e) => {
e.currentTarget.previousElementSibling.remove();
e.currentTarget.remove();
removeCircleHighlight();
btns.splice(0, 2);
round += 1;
isPlayerTurn = !isPlayerTurn;
nextRound(isPlayerTurn, round, isHard);
});
}
function addButtons() {
let count = parseInt(coinsChoiceEl.value);
if (isNaN(count)) {
return false;
} else {
if (count > 50 || count < 2) {
infoText.innerHTML = "Only >2 and <50 coins are supported!";
infoText.innerHTML = LOSS_ALERT_STYLE;
return false;
}
}
for (let num = 0; num < count; num++) {
let btn = document.createElement("button");
btn.innerHTML = "Coin " + (num + 1);
btn.classList = COIN_BTN_STYLE;
btnGroup.appendChild(btn);
btns.push(btn);
}
return true;
}
function cpuRemoveButtons(isHard) {
let numToDel;
let currNodeIndex = btns.length - 1;
removeCircleHighlight();
if (isHard) {
// TODO: when everything gets moved to proper class make this a method
let targetedNodes = links
.filter((link) => link.source.id === currNodeIndex)
.map((link) => link.target);
let idealMoves = targetedNodes.filter((node) => node.gs === 0);
if (idealMoves.length > 0) {
numToDel = currNodeIndex - idealMoves[0].id;
} else {
numToDel = Math.round(Math.random() + 1);
}
} else {
numToDel = Math.round(Math.random() + 1);
}
for (let n = 0; n < numToDel; n++) {
btns[n].remove();
}
btns.splice(0, numToDel);
}
function nextRound(isPlayerTurn, round, isHard) {
// Highlight in red the current number of coins on the network and optimal strat for player
if (btns.length > 0) {
highlightCircle(btns.length - 1, isPlayerTurn);
}
if (isPlayerTurn) {
if (btns.length === 1) {
infoText.innerHTML = "You LOSE!!";
infoText.classList = LOSS_ALERT_STYLE;
} else {
addButtonListeners(isPlayerTurn, round, isHard);
}
} else {
if (btns.length === 0) {
infoText.innerHTML = "You LOSE!!";
infoText.classList = LOSS_ALERT_STYLE;
} else if (btns.length === 1) {
infoText.innerHTML = "You WIN!";
infoText.classList = WIN_ALERT_STYLE;
} else {
infoText.innerHTML = "CPU choosing coin(s) to remove...";
infoText.classList = CPU_TURN_ALERT_STYLE;
setTimeout(() => {
cpuRemoveButtons(isHard);
isPlayerTurn = !isPlayerTurn;
round += 1;
nextRound(isPlayerTurn, round, isHard);
}, 2000);
}
}
}
function startGame() {
addButtons();
difficultyChoiceEl.disabled = true;
turnChoiceEl.disabled = true;
coinsChoiceEl.disabled = true;
startBtn.innerHTML = "Reset game";
startBtn.classList = RESET_BTN_STYLE;
startBtn.removeEventListener("click", startGame);
startBtn.addEventListener("click", resetGame);
let isPlayerTurn;
let turnChoice = turnChoiceEl.value;
if (turnChoice === "first") {
isPlayerTurn = true;
} else {
isPlayerTurn = false;
}
let isHard;
let diffChoice = difficultyChoiceEl.value;
if (diffChoice === "easy") {
isHard = false;
} else {
isHard = true;
}
visualizeNetwork();
nextRound(isPlayerTurn, 0, isHard);
}
function resetGame() {
for (let num = 0; num < btns.length; num++) {
btns[num].remove();
}
btns = [];
startBtn.innerHTML = "Start";
startBtn.classList = START_BTN_STYLE;
infoText.innerHTML = "Waiting for play...";
infoText.classList = READY_ALERT_STYLE;
networkEl.innerHTML = "";
difficultyChoiceEl.disabled = false;
turnChoiceEl.disabled = false;
coinsChoiceEl.disabled = false;
addStartListener();
}
function visualizeNetwork() {
let num = btns.length;
// nodes returns a [list] of {id: 1, fixed:true}
nodes = d3.range(num).map(function (d) {
return { id: d };
});
links = [];
for (let n = num - 1; n > 0; n--) {
links.push({ source: n, target: n - 1 });
if (n > 1) {
links.push({ source: n, target: n - 2 });
}
}
// Unmodified array for links and nodes currently
for (let n = 0; n < nodes.length; n++) {
let sourceLinks = links.filter((link) => link.source === n);
if (sourceLinks.length === 0) {
nodes[n].gs = 0;
} else if (sourceLinks.length === 1) {
nodes[n].gs = 1;
} else {
let targetIds = sourceLinks.map((link) => link.target);
let targetNodes = targetIds.map((nodeId) => nodes[nodeId]);
let targetGsVals = targetNodes.map((node) => node.gs);
let gs = mex(targetGsVals);
nodes[n].gs = gs;
}
}
let width = 500,
height = 500;
let force = d3.layout
.force()
.nodes(nodes)
.links(links)
.size([width, height]);
let svg = d3
.select("#network-analysis")
.append("svg")
.attr("width", width)
.attr("height", height);
// invisible circle for placing nodes
// it's actually two arcs so we can use the getPointAtLength() and getTotalLength() methods
let dim = width - 80;
let circle = svg
.append("path")
.attr(
"d",
"M 40, " +
(dim / 2 + 40) +
" a " +
dim / 2 +
"," +
dim / 2 +
" 0 1,0 " +
dim +
",0 a " +
dim / 2 +
"," +
dim / 2 +
" 0 1,0 " +
dim * -1 +
",0"
)
.style("fill", "#f5f5f5");
// evenly spaces nodes along arc
function circleCoord(node, index, num_nodes) {
let circumference = circle.node().getTotalLength();
function pointAtLength(l) {
return circle.node().getPointAtLength(l);
}
let sectionLength = circumference / num_nodes;
let position = sectionLength * index + sectionLength / 2;
return pointAtLength(circumference - position);
}
// fades out lines that node d doesn't connect to
function is_connected(d, opacity) {
lines.transition().style("stroke-opacity", function (o) {
return o.source === d ? 1 : opacity;
});
}
force.start();
// set coordinates for container nodes
nodes.forEach(function (n, i) {
let coord = circleCoord(n, i, nodes.length);
n.x = coord.x;
n.y = coord.y;
});
// use this one for straight line links...
lines = svg
.selectAll("line.node-link")
.data(links)
.enter()
.append("line")
.attr("stroke", "black")
.attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
gnodes = svg
.selectAll("g.gnode")
.data(nodes)
.enter()
.append("g")
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
})
.classed("gnode", true);
circles = gnodes
.append("circle")
.attr("r", 25)
.attr("class", "node")
.on("mouseenter", function (d) {
is_connected(d, 0.1);
circles.transition().duration(100).attr("r", 25);
d3.select(this).transition().duration(100).attr("r", 30);
})
.on("mouseleave", function (d) {
circles.transition().duration(100).attr("r", 25);
is_connected(d, 1);
});
labels = gnodes
.append("text")
.attr("dy", 4)
.text(function (d) {
return d.id + 1 + "," + d.gs;
});
}
addStartListener();
</script>
</html>