-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.mjs
102 lines (85 loc) · 2.54 KB
/
client.mjs
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
var allButtons = []
var moveCounter = 0;
var cheesesFound;
var noOfCheeses;
var gameHour;
let hostAddress = "https://AzureDemo-CheeseFinder.azurewebsites.net/";
let startUrl = hostAddress + "getstart.json";
let getStyleUrl = hostAddress + "getstyle.json";
function getFromServer(url, handler) {
fetch(url).then(response => {
response.text().then(result => {
handler(result);
}).catch(error => alert("Bad text: " + error));
}).catch(error => alert("Bad fetch: " + error));
}
function showCounters() {
let counterPar = document.getElementById("counterPar");
let cheesesLeft = noOfCheeses - cheesesFound;
counterPar.textContent = "Cheeses left:" + cheesesLeft + " Tries: " + moveCounter;
}
function fillGrid(buttons) {
for (let button of buttons) {
if (button.className == "empty") {
setButtonStyle(button);
}
}
}
function setButtonStyle(button) {
let x = button.getAttribute("x");
let y = button.getAttribute("y");
let checkUrl = getStyleUrl + "?x=" + x + "&y=" + y;
getFromServer(checkUrl, result => {
let checkDetails = JSON.parse(result);
if(checkDetails.hour != gameHour){
// we have reached the end of the hour
// end the game
alert("The game in this hour has ended.");
location.reload();
}
button.className = checkDetails.style;
if (button.className == "cheese") {
cheesesFound++;
if (cheesesFound == noOfCheeses) {
fillGrid(allButtons);
}
showCounters();
}
});
}
function buttonClickedHandler(event) {
let button = event.target;
if (button.className != "empty") {
return;
}
setButtonStyle(button);
moveCounter++;
showCounters();
}
function setupGame(gameDetailsJSON) {
let gameDetails = JSON.parse(gameDetailsJSON);
noOfCheeses = gameDetails.noOfCheeses;
gameHour = gameDetails.hour;
let container = document.getElementById("buttonPar");
for (let y = 0; y < gameDetails.height; y++) {
for (let x = 0; x < gameDetails.width; x++) {
let newButton = document.createElement("button");
newButton.className = "empty";
newButton.setAttribute("x", x);
newButton.setAttribute("y", y);
newButton.addEventListener("click", buttonClickedHandler);
newButton.textContent = "X";
container.appendChild(newButton);
allButtons.push(newButton);
}
let lineBreak = document.createElement("br");
container.appendChild(lineBreak);
}
showCounters();
}
function doPlayGame() {
moveCounter = 0;
cheesesFound = 0;
getFromServer(startUrl, setupGame);
}
export { doPlayGame };