forked from eric-wieser/snakes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ejs
582 lines (543 loc) · 16.1 KB
/
index.ejs
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
<!doctype html>
<html xmlns:og="http://opengraphprotocol.org/schema/">
<head>
<meta property="og:title" content="Snakes - A multiplayer game written in javascript using the HTML5 canvas, node.js, and Socket.IO"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="http://snakes.eric-wieser.tk/"/>
<meta property="og:description" content="A game for two (or more) players. Control the snakes with the arrow keys and WASD. Eat or be eaten!"/>
<meta property="og:image" content="http://eric-wieser.tk/images/snaps/snakes.png" />
<meta property="fb:admins" content="eric.wieser"/>
<link rel="shortcut icon" href="/favicon.png">
<script src="/socket.io/socket.io.js"></script>
<script src="browserify.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Dosis:300,600|Ubuntu" />
<style>
html, body {
background: #202020; width: 100%; height: 100%; margin: 0; padding: 0;
font-family: 'Dosis', Arial, sans-serif;
font-weight:300;
}
#message {
color: white;
position: absolute;
top:10px;
left: 0;
right: 0;
font-size: 30px;
text-align: center;
}
.score-bar {
position: absolute;
width: 100%;
height: 10px;
background: #808080;
}
.score-bar div {
position: absolute;
height: 10px;
}
.vertical-center {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table;
}
.vertical-center > div{
/*position: relative;
top: -50%;
left: -50%;*/
display: table-cell;
vertical-align: middle;
}
.vertical-center > div > div{
/*position: relative;
top: -50%;
left: -50%;*/
margin: auto;
}
h1{
background: #404040;
color: white;
margin: 0;
padding: 5px;
line-height: 40px;
font-size: 36px;
}
h2 {
color: #ff8000;
line-height: 30px;
font-size: 24px;
padding: 5px;
margin: 0;
}
p {
margin: 0;
padding: 5px;
font-family: Ubuntu;
line-height: 20px;
}
small {
padding: 5px;
font-family: Ubuntu;
color: #808080;
width: 100%;
text-align: center;
display: block;
}
a {
color: #ff8000;
border-bottom: 1px dotted #ff8000;
text-decoration: none;
}
.box {
border-top: 5px solid;
border-bottom: 5px solid;
/*box-shadow: 0 0 25px #404040;*/
overflow: hidden;
background: rgba(64, 64, 64, 0.5);
color: white;
}
#login .box{
width: 400px;
}
#login input{
width: 100%;
box-sizing: border-box;
margin: 0;
display: block;
padding: 0px;
height: 50px;
line-height: 50px;
font: inherit;
font-size: 40px;
border: none;
text-align: center;
outline: none;
background-color: transparent;
}
#login button {
display: none;
}
#about .box{
width: 80%;
}
#bottom {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
#scores {
font-size: 30px;
line-height: 35px;
padding: 0;
margin: 0;
width: 100%;
display: table;
}
#scores li {
display: table-row;
color: white;
}
#scores li span {
display: table-cell;
width: 50%;
}
#scores li span.name {
font-weight: 700;
text-align: right;
padding-right: 0.5em;
}
#chat input{
font: inherit;
height: 20px;
color: white;
padding: 0px;
margin: 0;
border: 0;
display: block;
width: 100%;
box-sizing: border-box;
background: transparent;
outline: none;
}
#chat .history {
color: white;
margin: 0;
padding: 0;
position: absolute;
bottom: 20px;
}
#chat .history li {
color: white;
padding: 0;
margin: 0;
word-wrap: break-word;
width: 100%;
}
#wrapper {
position: absolute;
top: 10px;
left: 0;
right: 0;
bottom: 0;
}
canvas {
width: 100%;
height: 100%;
display: block;
}
</style>
<title>Snakes - A multiplayer game written in javascript using the HTML5 canvas, node.js, and Socket.IO</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24953524-2']);
_gaq.push(['_setDomainName', 'eric-wieser.tk']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="wrapper"><canvas id="canvas">If you can see this, your browser sucks</canvas></div>
<div id="top">
<div id="message"></div>
<div class="score-bar">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div id="bottom">
<ul id="scores"></ul>
<form id="chat">
<ul class="history">
</ul>
<input />
<button type="submit" style="display: none"></button>
</form>
</div>
<div id="login" class="vertical-center">
<div>
<div class="box">
<h1>Snakes</h2>
<p>Control the snake by moving the mouse - no clicking required. Eat other snakes, or be eaten. <a href="#" id="about-link">About</a>.</p>
<form id="join">
<button type="submit">Join the game</button>
<input id="name" placeholder="Enter your name here" autocomplete="off" autofocus="autofocus" />
</form>
<small>Type your name above, and press Enter to join the game</small>
</div>
</div>
</div>
<div id="about" class="vertical-center" style="display: none">
<div>
<div class="box">
<h1>About Snakes</h1>
<p>Snakes started off as a simple physics engine, with just balls bouncing off each other and the edges of the screen. Then a form of magnetic attraction was simulated. Interestingly, the balls naturally formed into wriggling snake shapes. A couple more tweaks, and a set of balls followed the player. It began to become apparent that there was a potential for a game here. Add a second player, a scoring system, and the ability to eat other balls, and you have a single computer, keyboard-mashing game. You can still play a <a href="/local">2 player</a>, <a href="/local?3">3 player</a>, or even <a href="/local?4">4 player</a> version of the single-computer version.</p>
<h2>Networking</h2>
<p>Snakes needed improving. The controls were terrible, the arena too small, and most keyboards couldn't cope with the strain of 4 users each hammering arrow keys. It needed to go networked. Node.js was the answer, along with Socket.IO. This was an exercise in learning new technologies, and seeing where they led to. </p>
<h2>Created by <a href="http://eric-wieser.tk/">Eric Wieser</a></h2>
<p>With thanks to Max Sinclair for allowing a core of his webserver to be devoted to Snakes, Luke Suess and Jonathan Laver for game inspiration along the way, and numerous friends for playing, testing, and hacking the game so that it could be improved.</p>
<p>The inspiration to go networked came from Rob Hawkes' <a href="http://rawkets.com">Rawkets</a></p>
<p>Browse the source code <a href="http://github.com/eric-wieser/snakes">on github</a>
</div>
</div>
</div>
<script>
var events = require('events');
require('./color');
require('./snake');
require('./world');
require('./ball');
require('./entity');
var colorId = Math.random();
var color = Color.niceColor(colorId);
$('.box').css({
borderTopColor: color.toString(),
borderBottomColor: color.toString(),
});
$('a').css({
borderBottomColor: color.toString(),
});
$('#login input, h2, a').css({
color: color.toString()
});
$('#about .box').click(function(e) {
e.stopPropagation();
});
//Show and hide the about box
$('#about-link').click(function() {
$('#login')
.fadeOut()
.queue(function(next) { $('#about').fadeIn(next); })
.queue(function(next) { $('#about').one('click', next); })
.queue(function(next) { $('#about').fadeOut(next); })
.fadeIn();
return false;
})
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) {
window.setTimeout(function() {callback(Date.now())}, 1000 / 60.0);
};
//Get canvas stuff
var canvas = $('#canvas').get(0);
var width = canvas.width, height = canvas.height;
$(window).resize(function(){
width = canvas.width = $(canvas).width();
height = canvas.height = $(canvas).height();
}).resize();
// $(window).resize(function(){
// width = canvas.width = $(canvas).width();
// height = canvas.height = $(canvas).height();
// }).resize();
var ctx = canvas.getContext('2d');
var ball;
var opponents = {};
var keycodes = {
up: 87,
down: 83,
left: 65,
right: 68
};
var universe = new World(2000, 2000);
var socket = io.connect(':<%- port %>');
//var socket = io.connect('/');
var name;
var head;
var heads;
var viewOrigin = Vector.zero;
function nextViewOrigin() {
var x, y
if(!head) {
x = (universe.width - width) / 2;
y = (universe.height - height) / 2;
} else {
var border = 20;
x = head.position.x - width / 2;
y = head.position.y - height / 2;
if(x < -border)
x = -border;
else if(x > border + universe.width - width)
x = border + universe.width - width;
if(universe.width + 2 * border < width)
x = (universe.width - width) / 2;
if(y < -border)
y = -border;
else if(y > border + universe.height - height)
y = border + universe.height - height;
if(universe.height + 2 * border < height)
y = (universe.height - height) / 2;
}
return new Vector(x, y);
}
var nameinput = $('#name');
if(localStorage['name'])
nameinput.val(localStorage['name']);
var isTrying = false;
var playing = false;
$('#join').submit(function() {
//Stop things happening while the response is being waited for
if(!isTrying) {
isTrying = true;
n = nameinput.val();
socket.emit('join', {name: n, color: colorId}, function(data) {
if(data === true) {
localStorage['name'] = name = n;
$('#login').fadeOut(function() {
isTrying = false;
playing = true;
});
} else if(data instanceof Object && data.error) {
alert(data.error);
isTrying = false;
}
});
}
return false;
});
// socket.on('entityadded', function (data) {
// if(data.i in universe.entities) return;
// var b = new Ball(
// Vector.ify(data.p),
// data.r,
// Color.ify(data.c)
// );
// b._id = data.i; //probably going to regret this
// universe.addEntity(b);
// });
// socket.on('entitylost', function (id) {
// delete universe.entities[id];
// });
socket.on('servermessage', function (str) {
$('#message').html(str);
});
socket.on('ping', function() {
socket.emit('ping');
});
socket.on('scores', function (scores) {
//Get the DOM elements
var scoreList = $('#scores').empty();
var scoreBar = $('.score-bar').empty();
if(scores) {
//Keep track of left and rightmost bars
var mostLeft = 0;
var mostRight = 0;
scores.forEach(function(score, i) {
score = { name: score[0], value: score[1], color: score[2] };
//Add names to scoreboard
$('<li />').append(
$('<span class="name"/>').text(score.name), " ",
$('<span />').text(score.value)
).css('color', score.color).appendTo(scoreList);
//Pad out the bar, alternating sides
if(i%2 == 0) {
//left
$('<div />').css({
backgroundColor: score.color,
width: (score.value / 10) + '%',
left: (mostLeft / 10) + '%'
}).appendTo(scoreBar);
mostLeft += score.value;
}
else {
//right
$('<div />').css({
backgroundColor: score.color,
width: (score.value / 10) + '%',
right: (mostRight / 10) + '%'
}).appendTo(scoreBar);
mostRight += score.value;
}
});
}
});
socket.on('entityupdates', function (data) {
Object.forEach(data.e, function(edata, id) {
var p = Vector.ify(edata.p);
var c = Color.ify(edata.c);
var r = edata.r;
if(+id in universe.entities) {
var e = universe.entities[+id];
e.position = p;
e.color = c;
e.radius = r;
} else {
var b = new Ball(p, r, c);
b._id = +id;
universe.entities[+id] = b;
}
});
for(id in universe.entities)
if(!(id in data.e))
delete universe.entities[id];
var newHeads = {};
Object.forEach(data.s, function(id, name) {
newHeads[name] = universe.entities[id];
});
head = newHeads[name];
heads = newHeads;
if(playing) socket.emit('playercontrol', target.plus(viewOrigin));
});
var target = new Vector();
$(document).mousemove(function(e) {
var offset = $(canvas).offset();
target.set(e.pageX - offset.left, e.pageY - offset.top);
}).keydown(function() {
if(playing) $('#chat input').focus();
});
$('#chat').submit(function() {
if(playing) {
var input = $(this).find('input');
var msg = input.val();
input.val('');
socket.emit('chat', msg);
}
return false;
});
socket.on('chat', function (data) {
var name = data.n;
var color = Color.ify(data.c);
var message = data.m;
var history = $('#chat .history');
//alert(name + ":" + message);
$('<li />').text(' '+message).prepend(
$('<span />').css('color', color+"").text(name)
).appendTo('#chat .history');
while(history.children().size() > 10)
history.children().first().remove();
});
function drawArrow(x, y, angle) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(5, 0);
ctx.lineTo(20,-7.5);
ctx.lineTo(20, 7.5);
ctx.restore();
}
var lastt = Date.now();
function draw(t) {
//Calculate frame time
var dt = (t - lastt) / 1000.0;
ctx.clearRect(0, 0, width, height);
ctx.save();
viewOrigin = nextViewOrigin();
ctx.translate(-viewOrigin.x, -viewOrigin.y);
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 2000, 2000);
ctx.globalCompositeOperation = "lighter";
universe.entities.forEach(function(e) {
e.drawTo(ctx);
});
Object.forEach(heads, function(h) {
var off = {
left: h.position.x + h.radius < viewOrigin.x,
right: h.position.x - h.radius > viewOrigin.x + width,
top: h.position.y + h.radius < viewOrigin.y,
bottom: h.position.y - h.radius > viewOrigin.y + height
}
off.any = off.right || off.left || off.top || off.bottom;
if(!off.any) {
ctx.beginPath();
ctx.arc(h.position.x, h.position.y, h.radius / 2, 0, Math.PI * 2, false);
ctx.fillStyle = "white";
ctx.fill();
}
else {
if(off.left && off.top)
drawArrow(viewOrigin.x, viewOrigin.y, Math.PI / 4);
else if(off.right && off.top)
drawArrow(viewOrigin.x + width, viewOrigin.y, 3*Math.PI / 4);
else if(off.left && off.bottom)
drawArrow(viewOrigin.x, viewOrigin.y + height, -Math.PI / 4);
else if(off.right && off.bottom)
drawArrow(viewOrigin.x + width, viewOrigin.y + height, -3*Math.PI / 4);
else if(off.left)
drawArrow(viewOrigin.x, h.position.y, 0);
else if(off.right)
drawArrow(viewOrigin.x + width, h.position.y, Math.PI);
else if(off.top)
drawArrow(h.position.x, viewOrigin.y, Math.PI / 2);
else if(off.bottom)
drawArrow(h.position.x, viewOrigin.y + height, -Math.PI / 2);
ctx.fillStyle = h.color+"";
ctx.fill();
}
});
//prepare for next frame
lastt = t;
ctx.restore();
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
</script>
</body>
</html>