forked from mumud1/MiningBots-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
659 lines (595 loc) · 26.9 KB
/
game.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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
console.log("script started");
// Get hostname from cookie, otherwise leave as null
const server = document.cookie
.split("; ")
.find((row) => row.startsWith("lastServer="))
?.split("=")[1];
//Probably some default values for original testing:
// var hostname = "miningbots-api.dev.tk.sg";
// var port = 443;
var hostname = "localhost";
var port = 9003;
// if (server !== null) hostname = server;
var gameId;
var http_type = "http";
var ws_type = "ws";
// var http_type = "https";
// var ws_type = "wss";
//Dictionary of servers and respective names, urls
var servers = {
"p1.bootcamp.tk.sg": {
name: "Game 1",
url: "p1.bootcamp.tk.sg",
},
"p2.bootcamp.tk.sg": {
name: "Game 2",
url: "p2.bootcamp.tk.sg",
},
"p3.bootcamp.tk.sg": {
name: "Game 3",
url: "p3.bootcamp.tk.sg",
},
"p4.bootcamp.tk.sg": {
name: "Game 4",
url: "p4.bootcamp.tk.sg",
},
"p5.bootcamp.tk.sg": {
name: "Game 5",
url: "p5.bootcamp.tk.sg",
},
"p6.bootcamp.tk.sg": {
name: "Game 6",
url: "p6.bootcamp.tk.sg",
},
"p7.bootcamp.tk.sg": {
name: "Main Game",
url: "p7.bootcamp.tk.sg",
},
"p8.bootcamp.tk.sg": {
name: "Game 8",
url: "p8.bootcamp.tk.sg",
},
"p9.bootcamp.tk.sg": {
name: "Game 9",
url: "p9.bootcamp.tk.sg",
},
"p10.bootcamp.tk.sg": {
name: "Game 10",
url: "p10.bootcamp.tk.sg",
},
"s1.bootcamp.tk.sg": {
name: "Staging 1",
url: "s1.bootcamp.tk.sg",
},
"s2.bootcamp.tk.sg": {
name: "Staging 2",
url: "s2.bootcamp.tk.sg",
},
"s3.bootcamp.tk.sg": {
name: "Staging 3",
url: "s3.bootcamp.tk.sg",
},
"s4.bootcamp.tk.sg": {
name: "Staging 4",
url: "s4.bootcamp.tk.sg",
},
"s5.bootcamp.tk.sg": {
name: "Staging 5",
url: "s5.bootcamp.tk.sg",
},
"s6.bootcamp.tk.sg": {
name: "Staging 6",
url: "s6.bootcamp.tk.sg",
},
"s7.bootcamp.tk.sg": {
name: "Staging 7",
url: "s7.bootcamp.tk.sg",
},
"s8.bootcamp.tk.sg": {
name: "Staging 8",
url: "s8.bootcamp.tk.sg",
},
"s9.bootcamp.tk.sg": {
name: "Staging 9",
url: "s9.bootcamp.tk.sg",
},
"s10.bootcamp.tk.sg": {
name: "Staging 10",
url: "s10.bootcamp.tk.sg",
},
"localhost": {
name: "localhost",
url: "localhost",
},
"localhost": {
name: "localhost",
url: "localhost",
},
"miningbots-api.dev.tk.sg": {
name: "miningbots-api.dev.tk.sg",
url: "miningbots-api.dev.tk.sg",
},
};
// Variable to hold the selected server URL
let selectedServerUrl = null;
// Function to populate the dropdown menu
function populateDropdown() {
let dropdownMenu = document.querySelector(".dropdown-menu");
Object.keys(servers).forEach(function (key) {
let server = servers[key];
let menuItem = `<a class="dropdown-item" href="#" data-url="${server.url}">${server.name}</a>`;
dropdownMenu.innerHTML += menuItem;
});
}
// Event listener for dropdown item click
document.addEventListener("DOMContentLoaded", function () {
populateDropdown();
let dropdownItems = document.querySelectorAll(".dropdown-item");
dropdownItems.forEach(function (item) {
item.addEventListener("click", function (event) {
event.preventDefault();
selectedServerUrl = this.getAttribute("data-url");
console.log(selectedServerUrl);
let selectedServerName = this.textContent;
document.getElementById("navbarDropdownMenuLink").textContent =
selectedServerName;
// Save to cookie first
document.cookie = `lastServer=${selectedServerUrl}`;
location.reload();
// drawGame(selectedServerUrl, port);
});
});
});
// Player Name fetch code
async function fetchPlayerNames(gameId, playerIds) {
const url = `${http_type}://${hostname}:${port}/players`;
const playerRequest = { game_id: gameId, player_ids: playerIds };
try {
const response = await fetch(`${url}?request=${encodeURIComponent(JSON.stringify(playerRequest))}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const playerUpdates = await response.json();
return playerUpdates;
} catch (error) {
console.error('Failed to fetch player names:', error);
}
}
function drawGame(hostname, port) {
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
//Maybe adjust this to dynamically adapt such that the whole canvas will be shown regardless of map aspect ratio?
const GRID_SIZE = 32;
const images = {
kFactoryBot: new Image(),
kMiningBot: new Image(),
mixed_ore: new Image(),
granite: new Image(),
vibranium: new Image(),
adamantite: new Image(),
unobtanium: new Image(),
};
const terrainImages = {
unknown: new Image(),
grassland: new Image(),
hills: new Image(),
mountain: new Image()
};
//Assigns images
images.kFactoryBot.src = 'assets/Factory_Bot.png';
images.kMiningBot.src = 'assets/Mining_Bot.png';
images.mixed_ore.src = 'assets/Mixed_Ore.png';
images.granite.src = 'assets/Granite.png';
images.vibranium.src = 'assets/Vibranium.png';
images.adamantite.src = 'assets/Adamantite.png';
images.unobtanium.src = 'assets/Unobtanium.png';
terrainImages.unknown.src = 'assets/unknown.jpg';
terrainImages.grassland.src = 'assets/grassland.jpg';
terrainImages.hills.src = 'assets/hills.jpg';
terrainImages.mountain.src = 'assets/mountain.jpg';
//Likely connecting to the server and retrieving initial game state
fetch(`${http_type}://${hostname}:${port}/games`, {
method: 'GET'
})
.then(response => {
// console.log(response);
if (response.ok) {
// console.log('games:', response);
return response.json();
} else {
throw new Error(response.statusText);
}
})
.then(games => {
console.log('games:', games);
let gameId = games[0].game_id;
let gameStatus = games[0].game_status;
if (gameStatus == 'kEnded') {
console.log('failed to subscribe because game has ended');
return;
}
let fetch_map_config = fetch(`${http_type}://${hostname}:${port}/map_config?game_id=${gameId}`, {
method: 'GET'
});
return { response: fetch_map_config, game_id: gameId };
})
.then(async result => {
let response = await result.response;
if (response.ok) {
console.log('Second fetch response:', response);
return { map_config: response.json(), game_id: result.game_id };
} else {
throw new Error(response.statusText);
}
})
//Map config taken from server data
.then(async result => {
let map_config = await result.map_config;
console.log('map_config:', map_config);
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
const COLS = map_config.max_x;
const ROWS = map_config.max_y;
const MAX_WHITE_WIDTH = 60;
const MAX_WHITE_HEIGHT = 60;
const borderWidth = 1;
const GRID_SIZE = Math.min(screenWidth / COLS, screenHeight / ROWS); // fit the map on to the screen
console.log(COLS);
// Update canvas dimensions
canvas.width = COLS * GRID_SIZE;
canvas.height = ROWS * GRID_SIZE;
//Since final canvas dimensions are known, resize the container that holds canvas and DIV for bot-info DIVs
//This allows the bot-info DIVs to be directly right next to the game canvas without any ugly white space
document.getElementById("game-info-container").style = "display: grid; grid-template-columns: " + canvas.width + "px " + (screenWidth - canvas.width) + "px"
//Allows the bot-info container to take up as much remaining space as possible (on the right; not any space of game canvas)
document.getElementById("bot-info-megacontainer").style.width = screenWidth - canvas.width + "px"
let resource_configs = map_config.resource_configs;
const elements = {
kMiningBotOne: 0,
kFactoryBotOne: 1,
kMiningBotTwo: 2,
kFactoryBotTwo: 3,
unknown: 4,
traversable: 5,
resource: 6,
granite: 7,
vibranium: 8,
adamantite: 9,
unobtanium: 10
};
const resources = {
}
// let resource_configs = result.map_config.resource_configs;
//Adds new game elements from resource_configs if they do not already exist
resource_configs.forEach(resource => {
resources[Object.keys(resources).length] = resource.name;
});
let gameState = Array.from({ length: ROWS }, () => Array(COLS).fill(elements.unknown)); //all squares are unknown at the start
let terrains = Array.from({ length: ROWS }, () => Array(COLS).fill(terrainImages.unknown)); //all squares are unknown at teh start
function drawASquare(c, r, background, image) {
ctx.drawImage(background, c * GRID_SIZE - borderWidth, r * GRID_SIZE - borderWidth, GRID_SIZE + borderWidth, GRID_SIZE + borderWidth);
if (image) { //if an element image was given
ctx.drawImage(image, c * GRID_SIZE, r * GRID_SIZE, GRID_SIZE, GRID_SIZE);
}
}
//this exists because the bots have a background colour that indicates the player they are attached to, instead of the terrain
//can remove this if the background is also changed to an image
function drawABot(c, r, colour, image) {
ctx.fillStyle = colour;
ctx.fillRect(c * GRID_SIZE - borderWidth, r * GRID_SIZE - borderWidth, GRID_SIZE + borderWidth, GRID_SIZE + borderWidth);
ctx.drawImage(image, c * GRID_SIZE, r * GRID_SIZE, GRID_SIZE, GRID_SIZE);
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const element = gameState[row][col];
const terrain = terrains[row][col];
switch (element) {
case elements.kFactoryBotOne: // Blue
drawABot(col, row, '#25537b', images.kFactoryBot);
//drawASquare(col, row, terrain, images.kFactoryBot);
break;
case elements.kMiningBotOne: // Blue
drawABot(col, row, '#25537b', images.kMiningBot);
//drawASquare(col, row, terrain, images.kMiningBot);
break;
case elements.kFactoryBotTwo: // Red
drawABot(col, row, '#AA4344', images.kFactoryBot);
//drawASquare(col, row, terrain, images.kFactoryBot);
break;
case elements.kMiningBotTwo: // Red
drawABot(col, row, '#AA4344', images.kMiningBot);
//drawASquare(col, row, terrain, images.kMiningBot);
break;
case elements.unknown:
drawASquare(col, row, terrain); //nothing occupying the space, so no additional image
break;
case elements.traversable:
drawASquare(col, row, terrain); //nothing occupying the space, so no additional image
break;
case elements.resource:
ctx.drawImage(images.mixed_ore, col * GRID_SIZE, row * GRID_SIZE, GRID_SIZE, GRID_SIZE);
break;
case elements.granite:
drawASquare(col, row, terrain, images.granite);
break;
case elements.vibranium:
drawASquare(col, row, terrain, images.vibranium);
break;
case elements.adamantite:
drawASquare(col, row, terrain, images.adamantite);
break;
case elements.unobtanium:
drawASquare(col, row, terrain, images.unobtanium);
break;
}
if (COLS < MAX_WHITE_WIDTH && ROWS < MAX_WHITE_HEIGHT) { //if map is small enough, show white grid
ctx.strokeStyle = 'white'; // set border color to white
ctx.lineWidth = 1; // set border width
ctx.strokeRect(col * GRID_SIZE, row * GRID_SIZE, GRID_SIZE, GRID_SIZE);
}
}
}
}
// randomState();
render();
const ws = new WebSocket(`${ws_type}://${hostname}:${port}/observer`);
const botMap = new Map();
const jobMap = new Map();
const players = {};
const playerNames = {};
ws.onopen = function () {
console.log('Connected to WebSocket server');
const subscribeRequest = JSON.stringify({ game_id: result.game_id, observer_key: 514525537, observer_name: 'Observer' });
ws.send(subscribeRequest);
};
//When receiving message from the server, parses it and applies updates to game accordingly
ws.onmessage = function (msg) {
console.log('before parse:', msg);
try {
const data = JSON.parse(msg.data);
console.log('after parse:', data);
switch (data.update_type) {
case 'kTickUpdate':
console.log('tick update: ', data)
if (Array.isArray(data.bot_updates)) {
data.bot_updates.forEach(botUpdate => {
console.log('botUpdate: ', botUpdate);
updateBot(botUpdate, data.player_id);
})
}
if (Array.isArray(data.job_updates)) {
data.job_updates.forEach(jobUpdate => {
console.log('jobUpdate: ', jobUpdate);
updateJob(jobUpdate);
})
}
if (Array.isArray(data.land_updates)) {
data.land_updates.forEach(landUpdate => {
console.log('landUpdate: ', landUpdate);
updateLand(landUpdate);
})
}
updateUI(data.player_id);
render();
break;
case 'kEndInWin':
console.log(`game ended player id ${data.player_id} won`);
showWinner(data.player_id);
break;
case 'kEndInDraw':
console.log('game ended in draw');
break;
default:
console.log(data.UpdateType);
break;
}
} catch (error) {
console.error('Error parsing message:', error);
}
}
//Sidebars has to be dynamically added if in the future you want >2 players
const sidebars = [document.getElementById('bot-sidebar-one'), document.getElementById('bot-sidebar-two')];
//Possibly add more colours for >2 players too
const colors = ['blue', 'red', 'green', 'yellow', 'purple', 'orange', 'pink'];
//Updates the bot's position and its job?
function updateBot(botUpdate, playerId) {
if (!players.hasOwnProperty(playerId) && Object.keys(players).length < 2) {
players[playerId] = Object.keys(players).length;
}
const playerIndex = players[playerId];
const { id, position, variant, current_energy, current_job_id, cargo } = botUpdate;
if (botMap.has(id)) {
var oldPosition = botMap.get(id)[0];
var oldRow = ROWS - oldPosition.y - 1;
var oldCol = oldPosition.x;
gameState[oldRow][oldCol] = elements.traversable;
}
var job;
if (current_job_id == 0) {
job = { action: 'kNoAction', status: 'kNotStarted' };
} else if (jobMap.has(current_job_id)) {
job = jobMap.get(current_job_id);
} else {
job = { action: 'kNoAction', status: 'kNotStarted' };
}
botMap.set(id, [position, variant, current_energy, job, cargo, playerIndex]);
var newRow = ROWS - position.y - 1;
var newCol = position.x;
var playerNum = '';
if (playerIndex == 0) {
playerNum = 'One';
} else {
playerNum = 'Two';
}
var element = String(variant) + playerNum;
gameState[newRow][newCol] = elements[element];
renderBots();
}
//?
function updateJob(data) {
const { id, action, status } = data;
var job = { action: action, status: status }
jobMap.set(id, job);
}
//Updates the state of a tile on the map
function updateLand(data) {
const { position: { x, y }, is_traversable, resources, terrain_id } = data;
switch (terrain_id) {
case 0:
terrains[ROWS - y - 1][x] = terrainImages.grassland;
break;
case 1:
terrains[ROWS - y - 1][x] = terrainImages.hills;
break
case 2:
terrains[ROWS - y - 1][x] = terrainImages.mountain;
break;
default:
terrains[ROWS - y - 1][x] = terrainImages.unknown;
}
if (is_traversable) {
gameState[ROWS - y - 1][x] = elements.traversable;
} else {
if (Array.isArray(resources)) {
var highestId = -1;
resources.forEach(resource => {
if (resource.id > highestId) {
highestId = resource.id;
}
})
switch (highestId) {
case 0:
gameState[ROWS - y - 1][x] = elements.granite;
break;
case 1:
gameState[ROWS - y - 1][x] = elements.vibranium;
break;
case 2:
gameState[ROWS - y - 1][x] = elements.adamantite;
break;
case 3:
gameState[ROWS - y - 1][x] = elements.unobtanium;
break;
default:
gameState[ROWS - y - 1][x] = elements.resource;
break;
}
}
}
renderBots();
}
function nextGame() {
fetch(`${http_type}://${hostname}:${port}/games`, {
method: 'GET'
})
}
//Just the win screen
function showWinner(playerId) {
const winnerDiv = document.createElement('div');
winnerDiv.style.position = 'absolute';
winnerDiv.style.top = '50%';
winnerDiv.style.left = '50%';
winnerDiv.style.transform = 'translate(-50%, -50%)';
winnerDiv.style.padding = '20px';
winnerDiv.style.backgroundColor = 'white';
winnerDiv.style.border = '2px solid black';
winnerDiv.style.zIndex = '1000';
winnerDiv.innerHTML = `<h1>Player ${playerId} Won!</h1>`;
const closeButton = document.createElement('button');
closeButton.innerText = 'X';
closeButton.style.position = 'absolute';
closeButton.style.top = '-1px';
closeButton.style.right = '-1px';
closeButton.addEventListener('click', () => {
document.body.removeChild(winnerDiv);
});
winnerDiv.appendChild(closeButton);
document.body.appendChild(winnerDiv);
}
function renderBots() {
for (const [id, [position, variant, current_energy, job, cargo, playerIndex]] of botMap.entries()) {
var playerNum = '';
if (playerIndex == 0) {
playerNum = 'One';
} else {
playerNum = 'Two';
}
var element = String(variant) + playerNum;
gameState[ROWS - position.y - 1][position.x] = elements[element];
}
}
//shows a row for each player showing each bot and their data
async function updateUI(player_id) {
if (!players.hasOwnProperty(player_id) && Object.keys(players).length < 2) {
players[player_id] = Object.keys(players).length;
}
console.log('Players object:', players);
console.log('Current player ID:', player_id);
// Player names code:
let playerInfo = await fetchPlayerNames(gameId, [player_id]);
console.log(playerInfo);
// var name = playerInfo[0].name;
const playerIndex = players[player_id];
console.log('playerIndex:', playerIndex);
const sidebar = sidebars[playerIndex];
console.log('sidebar:', sidebar);
const color = colors[playerIndex];
sidebar.innerHTML = ''; // Clear the existing sidebar content
const header = document.createElement('h4');
header.textContent = `Player: ${player_id}`;
header.style.color = color;
header.style.fontSize = "0.8vw";
header.style.margin = "0vw";
header.style.padding = "0.05vw";
sidebar.appendChild(header);
const botBox = document.createElement('div');
botBox.style = "display: flex; gap: 0vw; padding: 0vw, margin: 0.1vw; height: 100%; width: 100%; overflow-y: auto";
sidebar.appendChild(botBox);
for (const [id, [position, variant, current_energy, job, cargo, botPlayerIndex]] of botMap.entries()) {
if (playerIndex == botPlayerIndex) { //THIS MIGHT NOT WORK
const botDiv = document.createElement('div');
console.log('cargo: ', cargo);
botDiv.classList.add('bot-info');
botDiv.style = "width: 14%, height: 24%";
botDiv.innerHTML = `
<h4 style="margin: 2px 0; padding: 0;"><b>${variant}</b> ${id}</h4>
<hr style="margin: 2px 0;">
<p style="margin: 2px 0; padding: 0;"><b>Position:</b> ${position.x}, ${position.y}</p>
<p style="margin: 2px 0; padding: 0;"><b>Energy:</b> ${current_energy}</p>
<p style="margin: 2px 0; padding: 0;"><b>Job:</b> ${job.action}</p>
<hr style="margin: 2px 0;">
`;
// , ${job.status}
const cargoContainer = document.createElement('div');
//Creating a grid: left side will be image of mineral, right side will be count of mineral
cargoContainer.style = "display: grid; grid-template-columns: auto auto; grid-gap: 0.05vw; padding: 0.1vw"
// Add each cargo item as a new paragraph
cargo.forEach(item => {
//Image of the mineral
let mineralImage = document.createElement('img')
mineralImage.src = "./assets/" + String(resources[item.id]) + ".png"
mineralImage.style = "width: 1vw; height: 1vw"
cargoContainer.appendChild(mineralImage);
//Text describing how much of the mineral there is
let mineralAmt = document.createElement('p')
mineralAmt.innerHTML = `${item.amount}`
cargoContainer.appendChild(mineralAmt)
});
// Append the cargo container to the botDiv
botDiv.appendChild(cargoContainer);
// Append the botDiv to the sidebar
botBox.appendChild(botDiv);
}
}
}
})
.catch((error) => {
console.error("Error:", error);
});
}
console.log(servers["localhost"].name);
document.getElementById("navbarDropdownMenuLink").textContent = hostname !== null ? servers[hostname].name : "Choose a server";
drawGame(hostname, port);