-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
377 lines (361 loc) · 15.3 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket Demo</title>
<style>
body {
margin: 0px;
padding: 0px;
overflow: hidden;
}
#game-screen {
display: none;
background-color: red;
width: 100%;
height: 100%;
}
#buttons {
position: fixed;
bottom: 20px;
left: 20px;
}
button.command {
width: 50px;
height: 50px;
}
#debug-list {
position: fixed;
bottom: 5px;
left: 5px;
font-size: 8px;
}
#chat-box {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
width: 50%;
}
#chat-box input[type="text"],
#chat-box textarea {
width: 100%;
font-size: 14x;
font-family: monospace;
background: transparent;
resize: none;
padding: 0px 0px;
padding-left: 1px;
border-style: solid;
border-color: rgba(0, 0, 0, 0.3);
border-width: 1px;
box-sizing: border-box;
}
#welcome-screen {
position: fixed;
background-color:#3498db;
width: 100%;
height: 100%;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 2;
cursor: pointer;
}
#welcome-container {
position: absolute;
top: 50%;
left: 50%;
font-size: 40px;
transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}
#welcome-choices button,
#welcome-choices input[type="text"] {
font-size: 40px;
}
#welcome-spinner {
border: 16px solid #f3f3f3;
border-top: 16px solid #3498db;
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="welcome-screen">
<div id="welcome-container">
<div id="welcome-explanation" style="text-align: center; font-size: 12px;">
The town is under attack by sinister ghosts.<br>
Become a warrior or sensor to save the town.<br>
Warriors can fight ghosts but cannot see them by themselves.<br>
Sensors can see ghosts but cannot fight them by themselves.<br>
However, they can collaborate:<br>
Sensors can mark ghosts, which makes them visible to warriors.<br>
<br>
Use WASD to move around.<br>
SPACE to mark/attack nearest ghost that is close enough.<br>
TAB to go in an out of chat box.<br>
ENTER to send chat message.<br>
</div>
<div id="welcome-choices">
Nickname:<br>
<input id="nickname-input" type="text" name="nickname">
<br>
Choose Class:<br>
<button onclick="chooseClass('warrior');">Warrior</button>
<button onclick="chooseClass('sensor');">Sensor</button>
</div>
<div id="welcome-spinner" style="display: none;"></div>
</div>
</div>
<div id="game-screen">
<canvas id="canvas">Game Arena</canvas>
<table id="buttons">
<tr>
<td></td>
<td><button class="command" onclick='ws.send(JSON.stringify({"type": "command", "command": "up"}))'>up (W)</button></td>
<td></td>
<td></td>
</tr>
<tr>
<td><button class="command" onclick='ws.send(JSON.stringify({"type": "command", "command": "left"}))'>left (A)</button></td>
<td><button class="command" onclick='ws.send(JSON.stringify({"type": "command", "command": "stop"}))'>stop</button></td>
<td><button class="command" onclick='ws.send(JSON.stringify({"type": "command", "command": "right"}))'>right (D)</button></td>
<td>
<button class="command" id="mark-button" style="display: none;" onclick='ws.send(JSON.stringify({"type": "command", "command": "mark"}))'>mark (SPACE)</button>
<button class="command" id="attack-button" style="display: none;" onclick='ws.send(JSON.stringify({"type": "command", "command": "attack"}))'>attack (SPACE)</button>
</td>
</tr>
<tr>
<td></td>
<td><button class="command" onclick='ws.send(JSON.stringify({"type": "command", "command": "down"}))'>down (S)</button></td>
<td></td>
<td></td>
</tr>
</table>
<ul id="debug-list"></ul>
<div id="chat-box">
<input id="chat-input" type="text" placeholder="Enter chat message to broadcast.">
<textarea id="chat-messages" readonly cols="80" rows="10" wrap="soft"></textarea>
</div>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const welcomeScreen = document.getElementById('welcome-screen');
const welcomeChoices = document.getElementById('welcome-choices');
const welcomeSpinner = document.getElementById('welcome-spinner');
const gameScreen = document.getElementById('game-screen');
const nickNameInput = document.getElementById('nickname-input');
const chatInput = document.getElementById('chat-input');
const chatMessages = document.getElementById('chat-messages');
var ws = null;
var actionCommand = null;
var GAME_INFO = {};
window.onload = window.onresize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.onkeydown = null;
function chooseClass(cls) {
playerClass = cls;
if (cls === "warrior") {
document.getElementById("attack-button").style.display = "inline";
actionCommand = 'attack';
}
else if (cls === "sensor") {
document.getElementById("mark-button").style.display = "inline";
actionCommand = 'mark';
}
var nickname = nickNameInput.value;
if (nickname === "") {
const names = ["Izuku Midoriya", "Katsuki Bakugo", "Shoto Todoroki", "Tenya Iida", "Ochaco Uraraka",
"Tsuyu Asui", "Fumikage Tokoyami", "Kyoka Jiro", "Momo Yaoyorozu", "Mei Hatsume"];
nickname = names[Math.floor(Math.random() * names.length)];
}
welcomeChoices.style.display = "none";
welcomeSpinner.style.display = "block";
var socketURL = null;
if (window.location.protocol === 'file:') {
socketURL = '127.0.0.1:8765';
}
else { // http:
socketURL = 'veliugurguney.com:83/socket';
}
ws = new WebSocket('ws://' + socketURL);
ws.onopen = function(event) {
var msg = {"type": "init", "nickname": nickname, "class": cls};
ws.send(JSON.stringify(msg));
console.log("first message sent ", msg);
};
ws.onmessage = function(event) {
var msg = JSON.parse(event.data);
for (var k of ['world_size', 'interaction_radius', 'sight_range']) {
GAME_INFO[k] = msg[k];
}
GAME_INFO['player_class'] = cls;
console.log("first message received ", msg);
startGameSession();
}
}
function render(units, cx, cy) {
// Arrage scale so that longer canvas side matches with player's sight
// There will be map area with unit data that won't be shown on the shorter side direction outside of canvas
var shorterSide = Math.max(canvas.width, canvas.height);
var scale = shorterSide / (GAME_INFO['sight_range'] * 2);
// Clear canvas
ctx.fillStyle = "rgb(200, 200, 200)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw world borders
ctx.lineWidth = 10;
ctx.strokeStyle = "rgb(160, 140, 105)";
ctx.strokeRect(-cx * scale + canvas.width / 2, -cy * scale + canvas.height / 2, GAME_INFO['world_size'] * scale, GAME_INFO['world_size'] * scale);
// Draw grid
ctx.lineWidth = 2;
ctx.strokeStyle = "rgba(255, 255, 255, 0.25)";
var gridSize = 5;
for (var k = -gridSize; k < GAME_INFO['sight_range'] * 2 + gridSize; k += gridSize) {
var deltaL = k * scale;
deltaX = deltaL - (cx % gridSize) * scale;
deltaY = deltaL - (cy % gridSize) * scale;
ctx.beginPath();
ctx.moveTo(deltaX, 0);
ctx.lineTo(deltaX, shorterSide);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, deltaY);
ctx.lineTo(shorterSide, deltaY);
ctx.stroke();
}
// Draw units
var isAlive = false;
var ghostColor = 'rgba(255, 0, 0, 0.25)';
for (var u of units) {
// translate unit coordinates to screen coordinate (shift (0, 0) to screen center)
x = u["x"] * scale + canvas.width / 2;
y = u["y"] * scale + canvas.height / 2;
if (u['type'] === 'ghost') {
ctx.fillStyle = ghostColor;
if (u['is_marked']) {
ctx.lineWidth = 2;
ctx.strokeStyle = 'green';
ctx.strokeRect(x - scale * 0.5, y - scale * 0.5, scale, scale); // unitSize == 1 is assumed
}
}
else if (u['type'] === 'me') {
isAlive = true;
ctx.fillStyle = 'blue';
ctx.lineWidth = 1;
ctx.strokeStyle = GAME_INFO['player_class'] === 'warrior' ? 'orange' : 'green';
ctx.beginPath();
var r = GAME_INFO['interaction_radius'] * scale;
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.stroke();
// Debug: borders of player sight
ctx.strokeStyle = 'black';
var sight = GAME_INFO['sight_range'] * scale;
ctx.strokeRect(x - sight, y - sight, 2 * sight, 2 * sight);
}
else if (u['type'] === 'player' && u['class'] === 'warrior') {
ctx.fillStyle = 'orange';
}
else if (u['type'] === 'player' && u['class'] === 'sensor') {
ctx.fillStyle = 'green';
}
ctx.fillRect(x - scale * 0.5, y - scale * 0.5, scale, scale);
ctx.font = "" + 0.5 * shorterSide / GAME_INFO['sight_range'] + "px Arial";
if ('nickname' in u) {
ctx.fillText(u['nickname'], x - scale * 0.5, y + scale * 1.5);
}
}
if (!isAlive) {
var gameOverMessage = [
"Unfortunately you passed away",
"and turned into a ghost.",
"Refresh to start again ",
"or spectate your ghost's haunting."
]
ctx.fillStyle = ghostColor;
for (var [ix, line] of gameOverMessage.entries()) {
ctx.fillText(line, 120, 100 + ix * 60);
}
}
}
function startGameSession() {
welcomeScreen.style.display = "none";
gameScreen.style.display = "block";
console.log("Entering game loop...");
ws.onmessage = function(event) {
var msg = JSON.parse(event.data);
if (msg["type"] === "game") {
var gameInfo = msg["game"];
var units = gameInfo['units'];
var cx = gameInfo['cx'];
var cy = gameInfo['cy'];
render(units, cx, cy);
var debugList = document.getElementById('debug-list');
var item = document.createElement('li');
content = document.createTextNode("tick no: " + gameInfo["tick_no"] + ", ts (server): " + gameInfo["ts"] + ", ts (client): " + Date.now() + ", lag: " + (new Date().getTime() - gameInfo["ts"] * 1000 + new Date().getTimezoneOffset() * 60 * 1000));
item.appendChild(content);
debugList.prepend(item);
if (debugList.children.length > 1) { // Keep 1 most recent items
debugList.removeChild(debugList.lastChild);
}
}
else if (msg["type"] === "chat") {
chatMessages.value = msg["chat"] + "\n" + chatMessages.value;
}
};
window.onkeydown = handleCommandKeyDown;
chatInput.onfocus = function() {
window.onkeydown = null;
};
chatInput.onblur = function(event) {
event.preventDefault();
window.onkeydown = handleCommandKeyDown;
}
chatInput.onkeydown = chatInput.onkeypress = function(event) {
if (event.keyCode === 13) {
var msg = JSON.stringify(
{"type": "chat", "chat": chatInput.value}
);
ws.send(msg);
chatInput.value = "";
chatInput.blur();
}
}
chatMessages.onfocus = function() {
chatMessages.blur();
}
}
function handleCommandKeyDown(event) {
if (event.repeat) { return; }
var command = null;
switch (event.keyCode) {
case 65: command = 'left'; break;
case 87: command = 'up'; break;
case 68: command = 'right'; break;
case 83: command = 'down'; break;
case 32: command = actionCommand; break;
case 9:
event.preventDefault();
chatInput.focus();
break;
default: return;
}
var msg = JSON.stringify(
{"type": "command", "command": command}
);
ws.send(msg);
};
</script>
</body>
</html>