Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b45f1bf3c0 | ||
|
|
f4ea4318c7 | ||
|
|
4afe0ecb70 |
No files matched your search
@@ -1 +0,0 @@
|
||||
/node_modules
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 theKidOfArcrania
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,14 +0,0 @@
|
||||
# Blockly.IO
|
||||
|
||||
This is a clone of the original Paper-IO released by Voodoo, except for one aspect. This will attempt to implement a multi-player aspect of the game (like a real IO game). Currently this has a playground at this [link] (https://thekidofarcrania.github.io/PaperIO-Web). It's a demo version of what to come. Hopefully by that time, the necessary server infrastructure could be obtained.
|
||||
|
||||
This is just a fun side-project for me. If you would want to use this code, it would be nice to let me know.
|
||||
|
||||
## Running
|
||||
|
||||
After cloning this repository, run the follow commands to install dependencies and set up server. Enjoy!
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
@@ -1,100 +0,0 @@
|
||||
|
||||
|
||||
function Color(h, s, l, a)
|
||||
{
|
||||
verifyRange(h, s, l);
|
||||
if (a === undefined) a = 1;
|
||||
else verifyRange(a);
|
||||
|
||||
Object.defineProperties(this, {
|
||||
"hue": {value: h, enumerable: true},
|
||||
"sat": {value: s, enumerable: true},
|
||||
"lum": {value: l, enumerable: true},
|
||||
"alpha": {value: a, enumerable: true},
|
||||
});
|
||||
}
|
||||
|
||||
Color.fromData = function(data) {
|
||||
return new Color(data.hue, data.sat, data.lum, data.alpha);
|
||||
};
|
||||
|
||||
function verifyRange()
|
||||
{
|
||||
for (var i = 0; i < arguments.length; i++)
|
||||
{
|
||||
if (arguments[i] < 0 || arguments[i] > 1)
|
||||
throw new RangeError("H, S, L, and A parameters must be between the range [0, 1]");
|
||||
}
|
||||
}
|
||||
|
||||
Color.prototype.interpolateToString = function(color, amount)
|
||||
{
|
||||
var rgbThis = hslToRgb(this.hue, this.sat, this.lum);
|
||||
var rgbThat = hslToRgb(color.hue, color.sat, color.lum);
|
||||
var rgb = [];
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
rgb[i] = Math.floor((rgbThat[i] - rgbThis[i]) * amount + rgbThis[i]);
|
||||
return {rgbString: function() {return 'rgb(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ')'}};
|
||||
}
|
||||
|
||||
Color.prototype.deriveLumination = function(amount)
|
||||
{
|
||||
var lum = this.lum + amount;
|
||||
lum = Math.min(Math.max(lum, 0), 1);
|
||||
return new Color(this.hue, this.sat, lum, this.alpha);
|
||||
};
|
||||
|
||||
Color.prototype.deriveHue = function(amount)
|
||||
{
|
||||
var hue = this.hue - amount;
|
||||
return new Color(hue - Math.floor(hue), this.sat, this.lum, this.alpha);
|
||||
};
|
||||
|
||||
Color.prototype.deriveSaturation = function(amount)
|
||||
{
|
||||
var sat = this.sat + amount;
|
||||
sat = Math.min(Math.max(sat, 0), 1);
|
||||
return new Color(this.hue, sat, this.lum, this.alpha);
|
||||
};
|
||||
|
||||
Color.prototype.deriveAlpha = function(newAlpha)
|
||||
{
|
||||
verifyRange(newAlpha);
|
||||
return new Color(this.hue, this.sat, this.lum, newAlpha);
|
||||
};
|
||||
|
||||
Color.prototype.rgbString = function() {
|
||||
var rgb = hslToRgb(this.hue, this.sat, this.lum);
|
||||
rgb[3] = this.a;
|
||||
return 'rgba(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ', ' + this.alpha + ')';
|
||||
};
|
||||
|
||||
|
||||
//http://stackoverflow.com/a/9493060/7344257
|
||||
function hslToRgb(h, s, l){
|
||||
var r, g, b;
|
||||
|
||||
if(s == 0){
|
||||
r = g = b = l; // achromatic
|
||||
}else{
|
||||
var hue2rgb = function hue2rgb(p, q, t){
|
||||
if(t < 0) t += 1;
|
||||
if(t > 1) t -= 1;
|
||||
if(t < 1/6) return p + (q - p) * 6 * t;
|
||||
if(t < 1/2) return q;
|
||||
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
|
||||
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
var p = 2 * l - q;
|
||||
r = hue2rgb(p, q, h + 1/3);
|
||||
g = hue2rgb(p, q, h);
|
||||
b = hue2rgb(p, q, h - 1/3);
|
||||
}
|
||||
|
||||
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
|
||||
}
|
||||
|
||||
module.exports = Color;
|
||||
@@ -1,2 +0,0 @@
|
||||
#!/bin/sh
|
||||
browserify game-client.js | uglifyjs -c > public/bundle.min.js
|
||||
-398
@@ -1,398 +0,0 @@
|
||||
/* global $ */
|
||||
var Player = require("./player.js");
|
||||
var renderer = require("./game-renderer.js");
|
||||
var consts = require("./game-consts.js");
|
||||
var core = require("./game-core.js");
|
||||
var io = require('socket.io-client');
|
||||
|
||||
var GRID_SIZE = consts.GRID_SIZE;
|
||||
var CELL_WIDTH = consts.CELL_WIDTH;
|
||||
|
||||
renderer.allowAnimation = true;
|
||||
|
||||
/**
|
||||
* Provides requestAnimationFrame in a cross browser way.
|
||||
* @author paulirish / http://paulirish.com/
|
||||
*/
|
||||
// window.requestAnimationFrame = function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
|
||||
// window.setTimeout( callback, 1000 / 60 );
|
||||
// };
|
||||
if ( !window.requestAnimationFrame ) {
|
||||
window.requestAnimationFrame = ( function() {
|
||||
return window.webkitRequestAnimationFrame ||
|
||||
window.mozRequestAnimationFrame ||
|
||||
window.oRequestAnimationFrame ||
|
||||
window.msRequestAnimationFrame ||
|
||||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
|
||||
window.setTimeout( callback, 1000 / 60 );
|
||||
};
|
||||
})();
|
||||
}
|
||||
|
||||
var norun = false;
|
||||
function run() {
|
||||
if (norun)
|
||||
return; //Prevent multiple clicks.
|
||||
norun = true;
|
||||
|
||||
user = null;
|
||||
deadFrames = 0;
|
||||
|
||||
//Socket connection.
|
||||
//, {transports: ['websocket'], upgrade: false}
|
||||
connectServer();
|
||||
socket.emit('hello', {
|
||||
name: $("#name").val(),
|
||||
type: 0, //Free-for-all
|
||||
gameid: -1 //Requested game-id, or -1 for anyone.
|
||||
}, function(success, msg) {
|
||||
if (success)
|
||||
{
|
||||
console.info("Connected to game!");
|
||||
$("#begin").addClass("hidden");
|
||||
$("#begin").animate({
|
||||
opacity: 0
|
||||
}, 1000);
|
||||
}
|
||||
else
|
||||
{
|
||||
console.error("Unable to connect to game: " + msg);
|
||||
var error = $("#error");
|
||||
error.text(msg);
|
||||
norun = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(function() {
|
||||
var error = $("#error");
|
||||
|
||||
if (!window.WebSocket)
|
||||
{
|
||||
error.text("Your browser does not support WebSockets!");
|
||||
return;
|
||||
}
|
||||
|
||||
error.text("Loading..."); //TODO: show loading screen.
|
||||
var success = false;
|
||||
var socket = io('http://' + window.location.hostname + ':8081', {
|
||||
'forceNew': true,
|
||||
upgrade: false,
|
||||
transports: ['websocket']
|
||||
});
|
||||
|
||||
socket.on('connect_error', function() {
|
||||
if (!success)
|
||||
error.text("Cannot connect with server. This probably is due to misconfigured proxy server. (Try using a different browser)");
|
||||
})
|
||||
socket.emit("checkConn", function() {
|
||||
success = true;
|
||||
socket.disconnect();
|
||||
});
|
||||
setTimeout(function() {
|
||||
if (!success)
|
||||
error.text("Cannot connect with server. This probably is due to misconfigured proxy server. (Try using a different browser)");
|
||||
else
|
||||
{
|
||||
error.text("");
|
||||
$("input").keypress(function(evt) {
|
||||
if (evt.which === 13)
|
||||
requestAnimationFrame(run);
|
||||
});
|
||||
$("button").click(function(evt) {
|
||||
requestAnimationFrame(run);
|
||||
});
|
||||
}
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
var user, socket, frame;
|
||||
|
||||
//Event listeners
|
||||
//Used from http://stackoverflow.com/a/23230280/7344257
|
||||
document.addEventListener('touchstart', handleTouchStart, false);
|
||||
document.addEventListener('touchmove', handleTouchMove, false);
|
||||
|
||||
var xDown = null;
|
||||
var yDown = null;
|
||||
|
||||
function handleTouchStart(evt) {
|
||||
xDown = evt.touches[0].clientX;
|
||||
yDown = evt.touches[0].clientY;
|
||||
}
|
||||
|
||||
function handleTouchMove(evt) {
|
||||
if ( xDown === null || yDown === null )
|
||||
return;
|
||||
|
||||
var xUp = evt.touches[0].clientX;
|
||||
var yUp = evt.touches[0].clientY;
|
||||
|
||||
var xDiff = xDown - xUp;
|
||||
var yDiff = yDown - yUp;
|
||||
|
||||
//Set new heading.
|
||||
var newHeading;
|
||||
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) /*most significant*/
|
||||
{
|
||||
if ( xDiff > 0 ) newHeading = 3; /* left swipe */
|
||||
else newHeading = 1; /* right swipe */
|
||||
}
|
||||
else
|
||||
{
|
||||
if ( yDiff > 0 ) newHeading = 0; /* up swipe */
|
||||
else newHeading = 2; /* down swipe */
|
||||
}
|
||||
setHeading(newHeading);
|
||||
|
||||
/* reset values */
|
||||
xDown = null;
|
||||
yDown = null;
|
||||
};
|
||||
|
||||
$(document).keydown(function(e) {
|
||||
if (!user || user.dead)
|
||||
return;
|
||||
var newHeading = -1;
|
||||
switch (e.which)
|
||||
{
|
||||
case 37: newHeading = 3; break; //LEFT
|
||||
case 38: newHeading = 0; break; //UP
|
||||
case 39: newHeading = 1; break; //RIGHT
|
||||
case 40: newHeading = 2; break; //DOWN
|
||||
default: return; //exit handler for other keys.
|
||||
}
|
||||
setHeading(newHeading);
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
function setHeading(newHeading)
|
||||
{
|
||||
if (newHeading === user.currentHeading || ((newHeading % 2 === 0) ^
|
||||
(user.currentHeading % 2 === 0)))
|
||||
{
|
||||
//user.heading = newHeading;
|
||||
if (socket)
|
||||
socket.emit("frame", {
|
||||
frame: frame,
|
||||
heading: newHeading
|
||||
}, function(success, msg) {
|
||||
if (!success)
|
||||
console.error(msg);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var grid = renderer.grid;
|
||||
var timeout = undefined;
|
||||
var dirty = false;
|
||||
var deadFrames = 0;
|
||||
var requesting = -1; //frame that we are requesting at.
|
||||
var frameCache = []; //Frames after our request.
|
||||
|
||||
//TODO: check if we can connect to server.
|
||||
function connectServer() {
|
||||
io.j = [];
|
||||
io.sockets = [];
|
||||
socket = io('http://' + window.location.hostname + ':8081', {
|
||||
'forceNew': true,
|
||||
upgrade: false,
|
||||
transports: ['websocket']
|
||||
});
|
||||
socket.on('connect', function(){
|
||||
console.info("Connected to server.");
|
||||
});
|
||||
socket.on('game', function(data) {
|
||||
if (timeout != undefined)
|
||||
clearTimeout(timeout);
|
||||
|
||||
//Initialize game.
|
||||
//TODO: display data.gameid --- game id #
|
||||
frame = data.frame;
|
||||
renderer.reset();
|
||||
|
||||
//Load players.
|
||||
data.players.forEach(function(p) {
|
||||
var pl = new Player(grid, p);
|
||||
renderer.addPlayer(pl);
|
||||
});
|
||||
user = renderer.getPlayerFromNum(data.num);
|
||||
if (!user) throw new Error();
|
||||
renderer.setUser(user);
|
||||
|
||||
//Load grid.
|
||||
var gridData = new Uint8Array(data.grid);
|
||||
for (var r = 0; r < grid.size; r++)
|
||||
for (var c = 0; c < grid.size; c++)
|
||||
{
|
||||
var ind = gridData[r * grid.size + c] - 1;
|
||||
grid.set(r, c, ind === -1 ? null : renderer.getPlayer(ind));
|
||||
}
|
||||
|
||||
renderer.paint();
|
||||
frame = data.frame;
|
||||
|
||||
if (requesting !== -1)
|
||||
{
|
||||
//Update those cache frames after we updated game.
|
||||
var minFrame = requesting;
|
||||
requesting = -1;
|
||||
while (frameCache.length > frame - minFrame)
|
||||
processFrame(frameCache[frame - minFrame]);
|
||||
frameCache = [];
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('notifyFrame', processFrame);
|
||||
|
||||
socket.on('dead', function() {
|
||||
socket.disconnect(); //In case we didn't get the disconnect call.
|
||||
});
|
||||
|
||||
socket.on('disconnect', function(){
|
||||
if (!user)
|
||||
return;
|
||||
console.info("Server has disconnected. Creating new game.");
|
||||
socket.disconnect();
|
||||
user.die();
|
||||
dirty = true;
|
||||
paintLoop();
|
||||
|
||||
showStats();
|
||||
//TODO: Show score stats.
|
||||
//Show score stats.
|
||||
// $("#stats").removeClass("hidden");
|
||||
// $("#stats").animate({
|
||||
// opacity: .9999
|
||||
// }, 3000, function() {
|
||||
|
||||
// });
|
||||
|
||||
//Then fade back into the login screen.
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
function showStats() {
|
||||
var stats =
|
||||
|
||||
$("#begin").removeClass("hidden");
|
||||
$("#begin").animate({
|
||||
opacity: .9999
|
||||
}, 1000, function() {
|
||||
$("#stats").addClass("hidden").css("opacity", 0);
|
||||
norun = false;
|
||||
});
|
||||
}
|
||||
|
||||
function processFrame(data)
|
||||
{
|
||||
if (timeout != undefined)
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (requesting !== -1 && requesting < data.frame)
|
||||
{
|
||||
frameCache.push(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.frame - 1 !== frame)
|
||||
{
|
||||
console.error("Frames don't match up!");
|
||||
socket.emit('requestFrame'); //Restore data.
|
||||
requesting = data.frame;
|
||||
frameCache.push(data);
|
||||
return;
|
||||
}
|
||||
|
||||
frame++;
|
||||
if (data.newPlayers)
|
||||
{
|
||||
data.newPlayers.forEach(function(p) {
|
||||
if (p.num === user.num)
|
||||
return;
|
||||
var pl = new Player(grid, p);
|
||||
renderer.addPlayer(pl);
|
||||
core.initPlayer(grid, pl);
|
||||
});
|
||||
}
|
||||
|
||||
var found = new Array(renderer.playerSize());
|
||||
data.moves.forEach(function(val, i) {
|
||||
var player = renderer.getPlayerFromNum(val.num);
|
||||
if (!player) return;
|
||||
if (val.left) player.die();
|
||||
found[i] = true;
|
||||
player.heading = val.heading;
|
||||
});
|
||||
for (var i = 0; i < renderer.playerSize(); i++)
|
||||
{
|
||||
//Implicitly leaving game.
|
||||
if (!found[i])
|
||||
{
|
||||
var player = renderer.getPlayer();
|
||||
player && player.die();
|
||||
}
|
||||
}
|
||||
|
||||
renderer.update();
|
||||
|
||||
var locs = {};
|
||||
for (var i = 0; i < renderer.playerSize(); i++)
|
||||
{
|
||||
var p = renderer.getPlayer(i);
|
||||
locs[p.num] = [p.posX, p.posY, p.waitLag];
|
||||
}
|
||||
|
||||
socket.emit("verify", {
|
||||
frame: frame,
|
||||
locs: locs
|
||||
}, function(frame, success, adviceFix, msg) {
|
||||
if (!success && requesting === -1)
|
||||
{
|
||||
console.error(frame + ": " + msg);
|
||||
if (adviceFix)
|
||||
socket.emit('requestFrame');
|
||||
}
|
||||
}.bind(this, frame));
|
||||
|
||||
dirty = true;
|
||||
requestAnimationFrame(function() {
|
||||
paintLoop();
|
||||
});
|
||||
timeout = setTimeout(function() {
|
||||
console.warn("Server has timed-out. Disconnecting.");
|
||||
socket.disconnect();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function paintLoop()
|
||||
{
|
||||
if (!dirty)
|
||||
return;
|
||||
renderer.paint();
|
||||
dirty = false;
|
||||
|
||||
if (user.dead)
|
||||
{
|
||||
if (timeout)
|
||||
clearTimeout(timeout);
|
||||
if (deadFrames === 60) //One second of frame
|
||||
{
|
||||
var before = renderer.allowAnimation;
|
||||
renderer.allowAnimation = false;
|
||||
renderer.update();
|
||||
renderer.paint();
|
||||
renderer.allowAnimation = before;
|
||||
user = null;
|
||||
deadFrames = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
socket.disconnect();
|
||||
deadFrames++;
|
||||
dirty = true;
|
||||
renderer.update();
|
||||
requestAnimationFrame(paintLoop);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
function constant(val)
|
||||
{
|
||||
return {
|
||||
value: val,
|
||||
enumerable: true
|
||||
};
|
||||
}
|
||||
|
||||
var consts = {
|
||||
GRID_SIZE: constant(80),
|
||||
CELL_WIDTH: constant(40),
|
||||
SPEED: constant(5),
|
||||
BORDER_WIDTH: constant(20),
|
||||
MAX_PLAYERS: constant(81)
|
||||
};
|
||||
|
||||
Object.defineProperties(module.exports, consts);
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
var ANIMATE_FRAMES = 24;
|
||||
var CELL_WIDTH = 40;
|
||||
|
||||
//TODO: remove constants.
|
||||
exports.initPlayer = function(grid, player)
|
||||
{
|
||||
for (var dr = -1; dr <= 1; dr++)
|
||||
for (var dc = -1; dc <= 1; dc++)
|
||||
if (!grid.isOutOfBounds(dr + player.row, dc + player.col))
|
||||
grid.set(dr + player.row, dc + player.col, player);
|
||||
};
|
||||
exports.updateFrame = function(grid, players, dead, notifyKill)
|
||||
{
|
||||
var adead = [];
|
||||
if (dead instanceof Array)
|
||||
adead = dead;
|
||||
|
||||
var kill;
|
||||
if (!notifyKill)
|
||||
kill = function() {};
|
||||
else
|
||||
kill = function(killer, other) {if (!removing[other]) notifyKill(killer, other);};
|
||||
|
||||
//Move players.
|
||||
var tmp = players.filter(function(val) {
|
||||
val.move();
|
||||
if (val.dead)
|
||||
adead.push(val);
|
||||
return !val.dead;
|
||||
});
|
||||
|
||||
//Remove players with collisions.
|
||||
var removing = new Array(players.length);
|
||||
for (var i = 0; i < players.length; i++)
|
||||
{
|
||||
for (var j = i; j < players.length; j++)
|
||||
{
|
||||
|
||||
//Remove those players when other players have hit their tail.
|
||||
if (!removing[j] && players[j].tail.hitsTail(players[i]))
|
||||
{
|
||||
kill(i, j);
|
||||
removing[j] = true;
|
||||
//console.log("TAIL");
|
||||
}
|
||||
if (!removing[i] && players[i].tail.hitsTail(players[j]))
|
||||
{
|
||||
kill(j, i);
|
||||
removing[i] = true;
|
||||
//console.log("TAIL");
|
||||
}
|
||||
|
||||
//Remove players with collisons...
|
||||
if (i !== j && squaresIntersect(players[i].posX, players[j].posX) &&
|
||||
squaresIntersect(players[i].posY, players[j].posY))
|
||||
{
|
||||
//...if one player is own his own territory, the other is out.
|
||||
if (grid.get(players[i].row, players[i].col) === players[i])
|
||||
{
|
||||
kill(i, j);
|
||||
removing[j] = true;
|
||||
}
|
||||
else if (grid.get(players[j].row, players[j].col) === players[j])
|
||||
{
|
||||
kill(j, i);
|
||||
removing[i] = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
//...otherwise, the one that sustains most of the collision will be removed.
|
||||
var areaI = area(players[i]);
|
||||
var areaJ = area(players[j]);
|
||||
|
||||
if (areaI === areaJ)
|
||||
{
|
||||
kill(i, j);
|
||||
kill(j, i);
|
||||
removing[i] = removing[j] = true;
|
||||
}
|
||||
else if (areaI > areaJ)
|
||||
{
|
||||
kill(j, i);
|
||||
removing[i] = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
kill(i, j);
|
||||
removing[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tmp = tmp.filter(function(val, i) {
|
||||
if (removing[i])
|
||||
{
|
||||
adead.push(val);
|
||||
val.die();
|
||||
}
|
||||
return !removing[i];
|
||||
});
|
||||
players.length = tmp.length;
|
||||
for (var i = 0; i < tmp.length; i++)
|
||||
players[i] = tmp[i];
|
||||
|
||||
//Remove dead squares.
|
||||
for (var r = 0; r < grid.size; r++)
|
||||
{
|
||||
for (var c = 0; c < grid.size; c++)
|
||||
{
|
||||
if (adead.indexOf(grid.get(r, c)) !== -1)
|
||||
grid.set(r, c, null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function squaresIntersect(a, b)
|
||||
{
|
||||
if (a < b)
|
||||
return b < a + CELL_WIDTH;
|
||||
else
|
||||
return a < b + CELL_WIDTH;
|
||||
}
|
||||
|
||||
function area(player)
|
||||
{
|
||||
var xDest = player.col * CELL_WIDTH;
|
||||
var yDest = player.row * CELL_WIDTH;
|
||||
|
||||
if (player.posX === xDest)
|
||||
return Math.abs(player.posY - yDest);
|
||||
else
|
||||
return Math.abs(player.posX - xDest);
|
||||
}
|
||||
@@ -1,466 +0,0 @@
|
||||
/* global $ */
|
||||
var Rolling = require("./rolling.js");
|
||||
var Color = require("./color.js");
|
||||
var Grid = require("./grid.js");
|
||||
var consts = require("./game-consts.js");
|
||||
var core = require("./game-core.js");
|
||||
|
||||
var GRID_SIZE = consts.GRID_SIZE;
|
||||
var CELL_WIDTH = consts.CELL_WIDTH;
|
||||
var SPEED = consts.SPEED;
|
||||
var BORDER_WIDTH = consts.BORDER_WIDTH;
|
||||
var SHADOW_OFFSET = 5;
|
||||
var ANIMATE_FRAMES = 24;
|
||||
var BOUNCE_FRAMES = [8, 4];
|
||||
var DROP_HEIGHT = 24;
|
||||
var DROP_SPEED = 2;
|
||||
var MIN_BAR_WIDTH = 65;
|
||||
var BAR_HEIGHT = SHADOW_OFFSET + CELL_WIDTH;
|
||||
var BAR_WIDTH = 400;
|
||||
|
||||
|
||||
var canvasWidth, canvasHeight, gameWidth, gameHeight, ctx, offctx, offscreenCanvas, initZoom;
|
||||
|
||||
$(function () {
|
||||
var canvas = $("#main-ui")[0];
|
||||
ctx = canvas.getContext('2d');
|
||||
|
||||
offscreenCanvas = document.createElement("canvas");
|
||||
offctx = offscreenCanvas.getContext('2d');
|
||||
|
||||
canvasWidth = offscreenCanvas.width = canvas.width = window.innerWidth;
|
||||
canvasHeight = offscreenCanvas.height = canvas.height = window.innerHeight - 20;
|
||||
zoom = initZoom = (canvasWidth / 1280);
|
||||
canvas.style.marginTop = 20 / 2;
|
||||
|
||||
gameWidth = canvasWidth;
|
||||
gameHeight = canvasHeight - BAR_HEIGHT;
|
||||
});
|
||||
|
||||
|
||||
var allowAnimation = true;
|
||||
var animateGrid, players, allPlayers, playerPortion, portionsRolling,
|
||||
barProportionRolling, grid, animateTo, offset, user, zoom, kills, showedDead;
|
||||
|
||||
grid = new Grid(GRID_SIZE, function(row, col, before, after) {
|
||||
//Keep track of areas.
|
||||
if (before)
|
||||
playerPortion[before.num]--;
|
||||
if (after)
|
||||
playerPortion[after.num]++;
|
||||
|
||||
//Queue animation
|
||||
if (before === after || !allowAnimation)
|
||||
return;
|
||||
animateGrid.set(row, col, {
|
||||
before: before,
|
||||
after: after,
|
||||
frame: 0
|
||||
});
|
||||
});
|
||||
|
||||
function init() {
|
||||
animateGrid = new Grid(GRID_SIZE);
|
||||
grid.reset();
|
||||
|
||||
players = [];
|
||||
allPlayers = [];
|
||||
playerPortion = [];
|
||||
portionsRolling = [];
|
||||
barProportionRolling = [];
|
||||
|
||||
animateTo = [0, 0];
|
||||
offset = [0, 0];
|
||||
|
||||
user = null;
|
||||
zoom = 1;
|
||||
kills = 0;
|
||||
showedDead = false;
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
//Paint methods.
|
||||
function paintGridBorder(ctx)
|
||||
{
|
||||
ctx.fillStyle = 'lightgray';
|
||||
var gridWidth = CELL_WIDTH * GRID_SIZE;
|
||||
|
||||
ctx.fillRect(-BORDER_WIDTH, 0, BORDER_WIDTH, gridWidth);
|
||||
ctx.fillRect(-BORDER_WIDTH, -BORDER_WIDTH, gridWidth + BORDER_WIDTH * 2, BORDER_WIDTH);
|
||||
ctx.fillRect(gridWidth, 0, BORDER_WIDTH, gridWidth);
|
||||
ctx.fillRect(-BORDER_WIDTH, gridWidth, gridWidth + BORDER_WIDTH * 2, BORDER_WIDTH);
|
||||
}
|
||||
|
||||
function paintGrid(ctx)
|
||||
{
|
||||
//Paint background.
|
||||
ctx.fillStyle = "#e2ebf3";
|
||||
ctx.fillRect(0, 0, CELL_WIDTH * GRID_SIZE, CELL_WIDTH * GRID_SIZE);
|
||||
|
||||
paintGridBorder(ctx);
|
||||
//paintGridLines(ctx);
|
||||
|
||||
//Get viewing limits
|
||||
var offsetX = (offset[0] - BORDER_WIDTH);
|
||||
var offsetY = (offset[1] - BORDER_WIDTH);
|
||||
|
||||
var minRow = Math.max(Math.floor(offsetY / CELL_WIDTH), 0);
|
||||
var minCol = Math.max(Math.floor(offsetX / CELL_WIDTH), 0);
|
||||
var maxRow = Math.min(Math.ceil((offsetY + gameHeight / zoom) / CELL_WIDTH), grid.size);
|
||||
var maxCol = Math.min(Math.ceil((offsetX + gameWidth / zoom) / CELL_WIDTH), grid.size);
|
||||
|
||||
//Paint occupied areas. (and fading ones).
|
||||
for (var r = minRow; r < maxRow; r++)
|
||||
{
|
||||
for (var c = minCol; c < maxCol; c++)
|
||||
{
|
||||
var p = grid.get(r, c);
|
||||
var x = c * CELL_WIDTH, y = r * CELL_WIDTH, baseColor, shadowColor;
|
||||
|
||||
var animateSpec = animateGrid.get(r, c);
|
||||
if (allowAnimation && animateSpec)
|
||||
{
|
||||
if (animateSpec.before) //fading animation
|
||||
{
|
||||
var frac = (animateSpec.frame / ANIMATE_FRAMES);
|
||||
var back = new Color(.58, .41, .92, 1);
|
||||
baseColor = animateSpec.before.baseColor.interpolateToString(back, frac);
|
||||
shadowColor = animateSpec.before.shadowColor.interpolateToString(back, frac);
|
||||
}
|
||||
else
|
||||
continue;
|
||||
}
|
||||
else if (p)
|
||||
{
|
||||
baseColor = p.baseColor;
|
||||
shadowColor = p.shadowColor;
|
||||
}
|
||||
else //No animation nor is this player owned.
|
||||
continue;
|
||||
|
||||
var hasBottom = !grid.isOutOfBounds(r + 1, c);
|
||||
var bottomAnimate = hasBottom && animateGrid.get(r + 1, c);
|
||||
var totalStatic = !bottomAnimate && !animateSpec;
|
||||
var bottomEmpty = totalStatic ? (hasBottom && !grid.get(r + 1, c)) :
|
||||
(!bottomAnimate || (bottomAnimate.after && bottomAnimate.before));
|
||||
if (hasBottom && ((!!bottomAnimate ^ !!animateSpec) || bottomEmpty))
|
||||
{
|
||||
|
||||
ctx.fillStyle = shadowColor.rgbString();
|
||||
ctx.fillRect(x, y + CELL_WIDTH, CELL_WIDTH + 1 / zoom, SHADOW_OFFSET);
|
||||
}
|
||||
ctx.fillStyle = baseColor.rgbString();
|
||||
ctx.fillRect(x, y, CELL_WIDTH + 1 / zoom, CELL_WIDTH + 1 / zoom);
|
||||
}
|
||||
}
|
||||
|
||||
if (!allowAnimation)
|
||||
return;
|
||||
|
||||
//Paint squares with drop in animation.
|
||||
for (var r = 0; r < grid.size; r++)
|
||||
{
|
||||
for (var c = 0; c < grid.size; c++)
|
||||
{
|
||||
animateSpec = animateGrid.get(r, c);
|
||||
x = c * CELL_WIDTH, y = r * CELL_WIDTH;
|
||||
|
||||
if (animateSpec && allowAnimation)
|
||||
{
|
||||
var viewable = r >= minRow && r < maxRow && c >= minCol && c < maxCol;
|
||||
if (animateSpec.after && viewable)
|
||||
{
|
||||
//Bouncing the squares.
|
||||
var offsetBounce = getBounceOffset(animateSpec.frame);
|
||||
y -= offsetBounce;
|
||||
|
||||
shadowColor = animateSpec.after.shadowColor;
|
||||
baseColor = animateSpec.after.baseColor.deriveLumination(-(offsetBounce / DROP_HEIGHT) * .1);
|
||||
|
||||
ctx.fillStyle = shadowColor.rgbString();
|
||||
ctx.fillRect(x, y + CELL_WIDTH, CELL_WIDTH, SHADOW_OFFSET);
|
||||
ctx.fillStyle = baseColor.rgbString();
|
||||
ctx.fillRect(x, y, CELL_WIDTH + 1 / zoom, CELL_WIDTH + 1 / zoom);
|
||||
}
|
||||
|
||||
animateSpec.frame++;
|
||||
if (animateSpec.frame >= ANIMATE_FRAMES)
|
||||
animateGrid.set(r, c, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: mobile-friendly UI bar and mobile-friendly ranks
|
||||
function paintUIBar(ctx)
|
||||
{
|
||||
var Z_CELL_WIDTH = CELL_WIDTH * initZoom;
|
||||
var Z_BAR_HEIGHT = BAR_HEIGHT * initZoom;
|
||||
var L_PADDING = 20 * initZoom;
|
||||
var PADDING = 10 * initZoom;
|
||||
var S_PADDING = 5 * initZoom;
|
||||
|
||||
//UI Bar background
|
||||
ctx.fillStyle = "#24422c";
|
||||
ctx.fillRect(0, 0, canvasWidth, Z_BAR_HEIGHT);
|
||||
|
||||
var barOffset;
|
||||
ctx.fillStyle = "white";
|
||||
ctx.font = "24px Changa";
|
||||
barOffset = (user && user.name) ? (ctx.measureText(user.name).width + L_PADDING) : 0;
|
||||
ctx.fillText(user ? user.name : "", S_PADDING, Z_CELL_WIDTH - S_PADDING);
|
||||
|
||||
//Draw filled bar.
|
||||
ctx.fillStyle = "rgba(180, 180, 180, .3)";
|
||||
ctx.fillRect(barOffset, 0, BAR_WIDTH * initZoom, Z_BAR_HEIGHT);
|
||||
|
||||
var userPortions = portionsRolling[user.num] ? portionsRolling[user.num].lag : 0;
|
||||
var barSize = Math.ceil(((BAR_WIDTH - MIN_BAR_WIDTH) * userPortions + MIN_BAR_WIDTH) * initZoom);
|
||||
ctx.fillStyle = user ? user.baseColor.rgbString() : "";
|
||||
ctx.fillRect(barOffset, 0, barSize, Z_CELL_WIDTH);
|
||||
ctx.fillStyle = user ? user.shadowColor.rgbString() : "";
|
||||
ctx.fillRect(barOffset, Z_CELL_WIDTH, barSize, SHADOW_OFFSET * initZoom);
|
||||
|
||||
//TODO: dont reset kill count and zoom when we request frames.
|
||||
//Percentage
|
||||
ctx.fillStyle = "white";
|
||||
ctx.font = "18px Changa";
|
||||
ctx.fillText((userPortions * 100).toFixed(3) + "%", S_PADDING + barOffset, Z_CELL_WIDTH - S_PADDING);
|
||||
|
||||
//Number of kills
|
||||
var killsText = "Kills: " + kills;
|
||||
var killsOffset = L_PADDING + BAR_WIDTH + barOffset;
|
||||
ctx.fillText(killsText, killsOffset, Z_CELL_WIDTH - S_PADDING);
|
||||
|
||||
//Calcuate rank
|
||||
var sorted = [];
|
||||
players.forEach(function(val) {
|
||||
sorted.push({player: val, portion: playerPortion[val.num]});
|
||||
});
|
||||
sorted.sort(function(a, b) {
|
||||
if (a.portion === b.portion) return a.player.num - b.player.num;
|
||||
else return b.portion - a.portion;
|
||||
});
|
||||
|
||||
var rank = sorted.findIndex(function(val) {return val.player === user});
|
||||
ctx.fillText("Rank: " + (rank === -1 ? "--" : rank + 1) + " of " + sorted.length,
|
||||
ctx.measureText(killsText).width + killsOffset + L_PADDING, Z_CELL_WIDTH - S_PADDING);
|
||||
|
||||
//Rolling the leaderboard bars.
|
||||
if (sorted.length > 0)
|
||||
{
|
||||
var maxPortion = sorted[0].portion;
|
||||
for (var i = 0; i < players.length; i++)
|
||||
{
|
||||
var rolling = barProportionRolling[players[i].num];
|
||||
rolling.value = playerPortion[players[i].num] / maxPortion;
|
||||
rolling.update();
|
||||
}
|
||||
}
|
||||
|
||||
//Show leaderboard.
|
||||
var leaderboardNum = Math.min(5, sorted.length);
|
||||
for (var i = 0; i < leaderboardNum; i++)
|
||||
{
|
||||
var player = sorted[i].player;
|
||||
var name = player.name || "Unnamed";
|
||||
var portion = barProportionRolling[player.num].lag;
|
||||
|
||||
var nameWidth = ctx.measureText(name).width;
|
||||
barSize = Math.ceil(((BAR_WIDTH - MIN_BAR_WIDTH) * portion + MIN_BAR_WIDTH) * initZoom);
|
||||
var barX = canvasWidth - barSize;
|
||||
var barY = Z_BAR_HEIGHT * (i + 1) * initZoom;
|
||||
var offset = i == 0 ? PADDING : 0;
|
||||
|
||||
ctx.fillStyle = 'rgba(10, 10, 10, .3)';
|
||||
ctx.fillRect(barX - PADDING, barY + PADDING - offset, barSize + PADDING, Z_BAR_HEIGHT + offset);
|
||||
ctx.fillStyle = player.baseColor.rgbString();
|
||||
ctx.fillRect(barX, barY, barSize, CELL_WIDTH * initZoom);
|
||||
ctx.fillStyle = player.shadowColor.rgbString();
|
||||
ctx.fillRect(barX, barY + CELL_WIDTH * initZoom, barSize, SHADOW_OFFSET * initZoom);
|
||||
|
||||
ctx.fillStyle = "black";
|
||||
ctx.fillText(name, barX - nameWidth - 15 * initZoom, barY + 27 * initZoom);
|
||||
|
||||
var percentage = (portionsRolling[player.num].lag * 100).toFixed(3) + "%";
|
||||
ctx.fillStyle = "white";
|
||||
ctx.fillText(percentage, barX + 5 * initZoom, barY + (CELL_WIDTH - 5) * initZoom);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function paint(ctx)
|
||||
{
|
||||
ctx.fillStyle = 'whitesmoke';
|
||||
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
|
||||
|
||||
//Move grid to viewport as said with the offsets, below the stats
|
||||
ctx.save();
|
||||
ctx.translate(0, BAR_HEIGHT);
|
||||
ctx.beginPath();
|
||||
ctx.rect(0, 0, gameWidth, gameHeight);
|
||||
ctx.clip();
|
||||
|
||||
//Zoom in/out based on player stats.
|
||||
ctx.scale(zoom, zoom);
|
||||
ctx.translate(-offset[0] + BORDER_WIDTH, -offset[1] + BORDER_WIDTH);
|
||||
|
||||
paintGrid(ctx);
|
||||
players.forEach(function (p) {
|
||||
var fr = p.waitLag;
|
||||
if (fr < ANIMATE_FRAMES)
|
||||
p.render(ctx, fr / ANIMATE_FRAMES);
|
||||
else
|
||||
p.render(ctx);
|
||||
});
|
||||
|
||||
//Reset transform to paint fixed UI elements
|
||||
ctx.restore();
|
||||
paintUIBar(ctx);
|
||||
|
||||
if ((!user || user.dead) && !showedDead)
|
||||
{
|
||||
showedDead = true;
|
||||
console.log("You died!");
|
||||
//return;
|
||||
}
|
||||
}
|
||||
|
||||
function paintDoubleBuff()
|
||||
{
|
||||
paint(offctx);
|
||||
ctx.drawImage(offscreenCanvas, 0, 0);
|
||||
}
|
||||
|
||||
function update() {
|
||||
|
||||
//Change grid offsets.
|
||||
for (var i = 0; i <= 1; i++)
|
||||
{
|
||||
if (animateTo[i] !== offset[i])
|
||||
{
|
||||
if (allowAnimation)
|
||||
{
|
||||
var delta = animateTo[i] - offset[i];
|
||||
var dir = Math.sign(delta);
|
||||
var mag = Math.min(SPEED, Math.abs(delta));
|
||||
offset[i] += dir * mag;
|
||||
}
|
||||
else
|
||||
offset[i] = animateTo[i];
|
||||
}
|
||||
}
|
||||
|
||||
//Calculate player portions.
|
||||
for (var i = 0; i < players.length; i++)
|
||||
{
|
||||
var roll = portionsRolling[players[i].num];
|
||||
roll.value = playerPortion[players[i].num] / GRID_SIZE / GRID_SIZE;
|
||||
roll.update();
|
||||
}
|
||||
|
||||
//Zoom goes from 1 to .5, decreasing as portion goes up. TODO: maybe can modify this?
|
||||
if (portionsRolling[user.num])
|
||||
zoom = initZoom / (portionsRolling[user.num].lag + 1);
|
||||
|
||||
var dead = [];
|
||||
core.updateFrame(grid, players, dead, function addKill(killer, other)
|
||||
{
|
||||
if (players[killer] === user && killer !== other)
|
||||
kills++;
|
||||
});
|
||||
dead.forEach(function(val) {
|
||||
console.log(val.name || "Unnamed" + " is dead");
|
||||
delete allPlayers[val.num];
|
||||
delete portionsRolling[val.num];
|
||||
});
|
||||
|
||||
//TODO: animate player is dead. (maybe explosion?), and tail rewinds itself.
|
||||
if (user) centerOnPlayer(user, animateTo);
|
||||
}
|
||||
|
||||
//Helper methods.
|
||||
function centerOnPlayer(player, pos)
|
||||
{
|
||||
var xOff = Math.floor(player.posX - (gameWidth / zoom - CELL_WIDTH) / 2);
|
||||
var yOff = Math.floor(player.posY - (gameHeight / zoom - CELL_WIDTH) / 2);
|
||||
var gridWidth = grid.size * CELL_WIDTH + BORDER_WIDTH * 2;
|
||||
pos[0] = Math.max(Math.min(xOff, gridWidth + (BAR_WIDTH + 100) / zoom - gameWidth / zoom), 0);
|
||||
pos[1] = Math.max(Math.min(yOff, gridWidth - gameHeight / zoom), 0);
|
||||
}
|
||||
|
||||
function getBounceOffset(frame)
|
||||
{
|
||||
var offsetBounce = ANIMATE_FRAMES;
|
||||
var bounceNum = BOUNCE_FRAMES.length - 1;
|
||||
while (bounceNum >= 0 && frame < offsetBounce - BOUNCE_FRAMES[bounceNum])
|
||||
{
|
||||
offsetBounce -= BOUNCE_FRAMES[bounceNum];
|
||||
bounceNum--;
|
||||
}
|
||||
|
||||
if (bounceNum === -1)
|
||||
{
|
||||
return (offsetBounce - frame) * DROP_SPEED;
|
||||
}
|
||||
else
|
||||
{
|
||||
offsetBounce -= BOUNCE_FRAMES[bounceNum];
|
||||
frame = frame - offsetBounce;
|
||||
var midFrame = BOUNCE_FRAMES[bounceNum] / 2;
|
||||
if (frame >= midFrame)
|
||||
return (BOUNCE_FRAMES[bounceNum] - frame) * DROP_SPEED;
|
||||
else
|
||||
return frame * DROP_SPEED;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports = exports = {
|
||||
addPlayer: function(player) {
|
||||
if (allPlayers[player.num])
|
||||
return; //Already added.
|
||||
allPlayers[player.num] = players[players.length] = player;
|
||||
playerPortion[player.num] = 0;
|
||||
portionsRolling[player.num] = new Rolling(9 / GRID_SIZE / GRID_SIZE, ANIMATE_FRAMES);
|
||||
barProportionRolling[player.num] = new Rolling(0, ANIMATE_FRAMES);
|
||||
return players.length - 1;
|
||||
},
|
||||
getPlayer: function(ind) {
|
||||
if (ind < 0 || ind >= players.length)
|
||||
throw new RangeError("Player index out of bounds (" + ind + ").");
|
||||
return players[ind];
|
||||
},
|
||||
getPlayerFromNum: function(num) {
|
||||
return allPlayers[num];
|
||||
},
|
||||
playerSize: function() {
|
||||
return players.length;
|
||||
},
|
||||
setUser: function(player) {
|
||||
user = player;
|
||||
centerOnPlayer(user, offset);
|
||||
},
|
||||
incrementKill: function() {
|
||||
kills++;
|
||||
},
|
||||
reset: function() {
|
||||
init();
|
||||
},
|
||||
paint: paintDoubleBuff,
|
||||
update: update
|
||||
};
|
||||
|
||||
Object.defineProperties(exports, {
|
||||
allowAnimation: {
|
||||
get: function() { return allowAnimation; },
|
||||
set: function(val) { allowAnimation = !!val; },
|
||||
enumerable: true
|
||||
},
|
||||
grid: {
|
||||
get: function() { return grid; },
|
||||
enumerable: true
|
||||
}
|
||||
});
|
||||
-311
@@ -1,311 +0,0 @@
|
||||
|
||||
var Color = require("./color");
|
||||
var Grid = require("./grid");
|
||||
var Player = require("./player");
|
||||
//var Gate = require("./gate");
|
||||
var core = require("./game-core");
|
||||
var consts = require("./game-consts");
|
||||
|
||||
var GRID_SIZE = consts.GRID_SIZE;
|
||||
var CELL_WIDTH = consts.CELL_WIDTH;
|
||||
var MAX_PLAYERS = consts.MAX_PLAYERS;
|
||||
|
||||
var HUES = [0, 10, 20, 25, 30, 35, 40, 45, 50, 60, 70, 100, 110, 120, 125, 130, 135, 140, 145, 150, 160, 170, 180, 190, 200, 210, 220].map(function(val) {return val / 240});
|
||||
var SATS = [192, 150, 100].map(function(val) {return val / 240});
|
||||
|
||||
|
||||
function Game(id)
|
||||
{
|
||||
//Shuffle the hues.
|
||||
for (var i = 0; i < HUES.length * 50; i++)
|
||||
{
|
||||
var a = Math.floor(Math.random() * HUES.length);
|
||||
var b = Math.floor(Math.random() * HUES.length);
|
||||
var tmp = HUES[a];
|
||||
HUES[a] = HUES[b];
|
||||
HUES[b] = tmp;
|
||||
}
|
||||
|
||||
var possColors = new Array(SATS.length * HUES.length);
|
||||
i = 0;
|
||||
for (var s = 0; s < SATS.length; s++)
|
||||
for (var h = 0; h < HUES.length; h++)
|
||||
possColors[i++] = new Color(HUES[h], SATS[s], .5, 1);
|
||||
|
||||
var nextInd = 0;
|
||||
var players = [];
|
||||
var newPlayers = [];
|
||||
var frameLocs = [];
|
||||
var frame = 0;
|
||||
|
||||
var filled = 0;
|
||||
var grid = new Grid(GRID_SIZE, function(row, col, before, after) {
|
||||
if (!!after ^ !!before)
|
||||
{
|
||||
if (after)
|
||||
filled++;
|
||||
else
|
||||
filled--;
|
||||
if (filled === GRID_SIZE * GRID_SIZE)
|
||||
console.log("FULL GAME");
|
||||
}
|
||||
});
|
||||
|
||||
this.id = id;
|
||||
|
||||
this.addPlayer = function(client, name) {
|
||||
if (players.length >= MAX_PLAYERS)
|
||||
return false;
|
||||
|
||||
var start = findEmpty(grid);
|
||||
if (!start)
|
||||
return false;
|
||||
|
||||
var params = {
|
||||
posX: start.col * CELL_WIDTH,
|
||||
posY: start.row * CELL_WIDTH,
|
||||
currentHeading: Math.floor(Math.random() * 4),
|
||||
name: name,
|
||||
num: nextInd,
|
||||
base: possColors.shift()
|
||||
};
|
||||
|
||||
var p = new Player(grid, params);
|
||||
p.tmpHeading = params.currentHeading;
|
||||
p.client = client;
|
||||
players.push(p);
|
||||
newPlayers.push(p);
|
||||
nextInd++;
|
||||
core.initPlayer(grid, p);
|
||||
|
||||
console.log((p.name || "Unnamed") + " (" + p.num + ") joined.");
|
||||
|
||||
client.on("requestFrame", function () {
|
||||
if (p.frame === frame)
|
||||
return;
|
||||
p.frame = frame; //Limit number of requests per frame. (One per frame);
|
||||
|
||||
var splayers = players.map(function(val) {return val.serialData();});
|
||||
client.emit("game", {
|
||||
"num": p.num,
|
||||
"gameid": id,
|
||||
"frame": frame,
|
||||
"players": splayers,
|
||||
"grid": gridSerialData(grid, players)
|
||||
});
|
||||
});
|
||||
|
||||
//Verifies that this client has executed this frame properly.
|
||||
client.on("verify", function(data, resp) {
|
||||
if (typeof resp !== "function")
|
||||
return;
|
||||
|
||||
if (!data.frame)
|
||||
resp(false, false, "No frame supplied");
|
||||
else if (!checkInt(data.frame, 0, frame + 1))
|
||||
resp(false, false, "Must be a valid frame number");
|
||||
else
|
||||
{
|
||||
verifyPlayerLocations(data.frame, data.locs, resp);
|
||||
}
|
||||
});
|
||||
|
||||
client.on("frame", function(data, errorHan){
|
||||
if (typeof data === "function")
|
||||
{
|
||||
errorHan(false, "No data supplied.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof errorHan !== "function")
|
||||
errorHan = function() {};
|
||||
|
||||
if (!data)
|
||||
errorHan(false, "No data supplied.");
|
||||
else if (!checkInt(data.frame, 0, Infinity))
|
||||
errorHan(false, "Requires a valid non-negative frame integer.");
|
||||
else if (data.frame > frame)
|
||||
errorHan(false, "Invalid frame received.");
|
||||
else
|
||||
{
|
||||
if (data.heading !== undefined)
|
||||
{
|
||||
if (checkInt(data.heading, 0, 4))
|
||||
{
|
||||
p.tmpHeading = data.heading;
|
||||
errorHan(true);
|
||||
}
|
||||
else
|
||||
errorHan(false, "New heading must be an integer of range [0, 4).");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
client.on('disconnect', function() {
|
||||
p.die(); //Die immediately if not already.
|
||||
p.disconnected = true;
|
||||
console.log((p.name || "Unnamed") + " (" + p.num + ") left.");
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
function pushPlayerLocations()
|
||||
{
|
||||
var locs = [];
|
||||
for (var p of players)
|
||||
locs[p.num] = [p.posX, p.posY, p.waitLag];
|
||||
locs.frame = frame;
|
||||
|
||||
if (frameLocs.length >= 300) //Give it 5 seconds of lag.
|
||||
frameLocs.shift();
|
||||
frameLocs.push(locs);
|
||||
}
|
||||
|
||||
function verifyPlayerLocations(fr, verify, resp)
|
||||
{
|
||||
var minFrame = frame - frameLocs.length + 1;
|
||||
if (fr < minFrame || fr > frame)
|
||||
{
|
||||
resp(false, false, "Frames out of reference");
|
||||
return;
|
||||
}
|
||||
|
||||
function string(loc)
|
||||
{
|
||||
return '(' + loc[0] + ', ' + loc[1] + ') [' + loc[2] + ']';
|
||||
}
|
||||
|
||||
var locs = frameLocs[fr - minFrame];
|
||||
if (locs.frame !== fr)
|
||||
{
|
||||
resp(false, false, locs.frame + " != " + fr);
|
||||
return;
|
||||
}
|
||||
for (var num in verify)
|
||||
{
|
||||
if (locs[num][0] !== verify[num][0] || locs[num][1] !== verify[num][1] || locs[num][2] !== verify[num][2])
|
||||
{
|
||||
resp(false, true, 'P' + num + ' ' + string(locs[num]) + ' !== ' + string(verify[num]));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
resp(true, false);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
|
||||
//TODO: notify those players that this server automatically drops out.
|
||||
var splayers = players.map(function(val) {return val.serialData();});
|
||||
var snews = newPlayers.map(function(val) {
|
||||
//Emit game stats.
|
||||
val.client.emit("game", {
|
||||
"num": val.num,
|
||||
"gameid": id,
|
||||
"frame": frame,
|
||||
"players": splayers,
|
||||
"grid": gridSerialData(grid, players),
|
||||
});
|
||||
return val.serialData();
|
||||
});
|
||||
var moves = players.map(function(val) {
|
||||
//Account for race condition (when heading is set after emitting frames, and before updating).
|
||||
val.heading = val.tmpHeading;
|
||||
return {num: val.num, left: !!val.disconnected, heading: val.heading};
|
||||
});
|
||||
|
||||
update();
|
||||
|
||||
var data = {frame: frame + 1, moves: moves};
|
||||
if (snews.length > 0)
|
||||
{
|
||||
data.newPlayers = snews;
|
||||
newPlayers = [];
|
||||
}
|
||||
|
||||
for (var pl of players)
|
||||
pl.client.emit("notifyFrame", data);
|
||||
|
||||
frame++;
|
||||
pushPlayerLocations();
|
||||
}
|
||||
|
||||
this.tickFrame = tick;
|
||||
|
||||
function update()
|
||||
{
|
||||
var dead = [];
|
||||
core.updateFrame(grid, players, dead);
|
||||
for (var pl of dead)
|
||||
{
|
||||
if (!pl.handledDead)
|
||||
{
|
||||
possColors.unshift(pl.baseColor);
|
||||
pl.handledDead = true;
|
||||
}
|
||||
console.log((pl.name || "Unnamed") + " (" + pl.num + ") died.");
|
||||
pl.client.emit("dead");
|
||||
pl.client.disconnect(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkInt(value, min, max)
|
||||
{
|
||||
if (typeof value !== "number")
|
||||
return false;
|
||||
if (value < min || value >= max)
|
||||
return false;
|
||||
if (Math.floor(value) !== value)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function gridSerialData(grid, players)
|
||||
{
|
||||
var buff = Buffer.alloc(grid.size * grid.size);
|
||||
|
||||
var numToIndex = new Array(players.length > 0 ? players[players.length - 1].num + 1 : 0);
|
||||
for (var i = 0; i < players.length; i++)
|
||||
numToIndex[players[i].num] = i + 1;
|
||||
|
||||
for (var r = 0; r < grid.size; r++)
|
||||
for (var c = 0; c < grid.size; c++)
|
||||
{
|
||||
var ele = grid.get(r, c);
|
||||
buff[r * grid.size + c] = ele ? numToIndex[ele.num] : 0;
|
||||
}
|
||||
return buff;
|
||||
}
|
||||
|
||||
function findEmpty(grid)
|
||||
{
|
||||
var available = [];
|
||||
|
||||
for (var r = 1; r < grid.size - 1; r++)
|
||||
for (var c = 1; c < grid.size - 1; c++)
|
||||
{
|
||||
var cluttered = false;
|
||||
checkclutter: for (var dr = -1; dr <= 1; dr++)
|
||||
{
|
||||
for (var dc = -1; dc <= 1; dc++)
|
||||
{
|
||||
if (grid.get(r + dr, c + dc))
|
||||
{
|
||||
cluttered = true;
|
||||
break checkclutter;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!cluttered)
|
||||
available.push({row: r, col: c});
|
||||
}
|
||||
|
||||
if (available.length === 0)
|
||||
return null;
|
||||
else
|
||||
return available[Math.floor(available.length * Math.random())];
|
||||
}
|
||||
|
||||
module.exports = Game;
|
||||
@@ -1,47 +0,0 @@
|
||||
var inherits = require('util').inherits;
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
|
||||
module.exports = Gate;
|
||||
|
||||
function Gate(awaiting)
|
||||
{
|
||||
var _this = this;
|
||||
if (!(this instanceof Gate))
|
||||
return new Gate(awaiting);
|
||||
|
||||
if (typeof awaiting !== "number")
|
||||
awaiting = 0;
|
||||
|
||||
var currentAwaiting = awaiting;
|
||||
var readyCount = 0;
|
||||
var ready = new Array(currentAwaiting);
|
||||
|
||||
this.setAwaiting = function(count) {
|
||||
awaiting = count;
|
||||
};
|
||||
this.ready = function(ind) {
|
||||
if (Math.floor(ind) != ind || ind >= readyCount)
|
||||
return false;
|
||||
|
||||
ready[ind] = true;
|
||||
readyCount++;
|
||||
|
||||
_this.emit("ready", ind);
|
||||
if (readyCount >= currentAwaiting)
|
||||
{
|
||||
_this.emit("allReady");
|
||||
_this.reset();
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
this.reset = function() {
|
||||
_this.emit("reset");
|
||||
ready = new Array(currentAwaiting = awaiting);
|
||||
readyCount = 0;
|
||||
};
|
||||
|
||||
EventEmitter.call(this);
|
||||
}
|
||||
|
||||
inherits(Gate, EventEmitter);
|
||||
@@ -1,56 +0,0 @@
|
||||
function Grid(size, changeCallback)
|
||||
{
|
||||
var grid = new Array(size);
|
||||
var modified = false;
|
||||
|
||||
var data = {
|
||||
grid: grid,
|
||||
size: size
|
||||
};
|
||||
|
||||
this.get = function(row, col)
|
||||
{
|
||||
if (isOutOfBounds(data, row, col))
|
||||
throw new RangeError("Row or Column value out of bounds");
|
||||
return grid[row] && grid[row][col];
|
||||
}
|
||||
this.set = function(row, col, value)
|
||||
{
|
||||
if (isOutOfBounds(data, row, col))
|
||||
throw new RangeError("Row or Column value out of bounds");
|
||||
|
||||
if (!grid[row])
|
||||
grid[row] = new Array(size);
|
||||
var before = grid[row][col];
|
||||
grid[row][col] = value;
|
||||
|
||||
if (typeof changeCallback === "function")
|
||||
changeCallback(row, col, before, value);
|
||||
|
||||
modified = true;
|
||||
|
||||
return before;
|
||||
}
|
||||
this.reset = function() {
|
||||
if (modified)
|
||||
{
|
||||
grid = new Array(size);
|
||||
modified = false;
|
||||
}
|
||||
}
|
||||
|
||||
this.isOutOfBounds = isOutOfBounds.bind(this, data);
|
||||
|
||||
Object.defineProperty(this, "size", {
|
||||
get: function() {return size; },
|
||||
enumerable: true
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function isOutOfBounds(data, row, col)
|
||||
{
|
||||
return row < 0 || row >= data.size || col < 0 || col >= data.size;
|
||||
}
|
||||
|
||||
module.exports = Grid;
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<head>
|
||||
<link href="https://fonts.googleapis.com/css?family=Changa:600" rel="stylesheet">
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
|
||||
<script src="bundle.js"></script>
|
||||
<style>
|
||||
body, html {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
background: black;
|
||||
}
|
||||
|
||||
canvas {
|
||||
image-rendering: optimizeSpeed; /* Older versions of FF */
|
||||
image-rendering: -moz-crisp-edges; /* FF 6.0+ */
|
||||
image-rendering: -webkit-optimize-contrast; /* Safari */
|
||||
image-rendering: -o-crisp-edges; /* OS X & Windows Opera (12.02+) */
|
||||
image-rendering: pixelated; /* Awesome future-browsers */
|
||||
-ms-interpolation-mode: nearest-neighbor; /* IE */
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="main-ui"></canvas>
|
||||
</body>
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "blockly-io",
|
||||
"version": "0.9.0",
|
||||
"description": "An multiplayer-IO type game (cloned from Paper-IO)",
|
||||
"main": "",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/theKidOfArcrania/Blockly-IO.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Blockly-IO",
|
||||
"Paper-IO",
|
||||
"IO",
|
||||
"Game"
|
||||
],
|
||||
"author": "theKidOfArcrania",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/theKidOfArcrania/Blockly-IO/issues"
|
||||
},
|
||||
"homepage": "https://github.com/theKidOfArcrania/Blockly-IO#readme",
|
||||
"dependencies": {
|
||||
"compression": "^1.6.2",
|
||||
"express": "^4.15.0",
|
||||
"finalhandler": "^1.0.0",
|
||||
"serve-static": "^1.11.2",
|
||||
"socket.io": "^1.7.3",
|
||||
"socket.io-client": "^1.7.3",
|
||||
"socket.io-proxy": "^1.0.3"
|
||||
}
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
var Stack = require("./stack.js");
|
||||
var Color = require("./color.js");
|
||||
var Grid = require("./grid.js");
|
||||
var consts = require("./game-consts.js");
|
||||
|
||||
var GRID_SIZE = consts.GRID_SIZE;
|
||||
var CELL_WIDTH = consts.CELL_WIDTH;
|
||||
var NEW_PLAYER_LAG = 60; //wait for a second at least.
|
||||
|
||||
function defineGetter(getter) {
|
||||
return {
|
||||
get: getter,
|
||||
enumerable: true
|
||||
};
|
||||
}
|
||||
|
||||
function defineInstanceMethods(thisobj, data /*, methods...*/)
|
||||
{
|
||||
for (var i = 2; i < arguments.length; i++)
|
||||
thisobj[arguments[i].name] = arguments[i].bind(this, data);
|
||||
}
|
||||
|
||||
function defineAccessorProperties(thisobj, data /*, names...*/)
|
||||
{
|
||||
var descript = {};
|
||||
function getAt(name) { return function() {return data[name] } }
|
||||
for (var i = 2; i < arguments.length; i++)
|
||||
descript[arguments[i]] = defineGetter(getAt(arguments[i]));
|
||||
Object.defineProperties(thisobj, descript);
|
||||
}
|
||||
|
||||
function TailMove(orientation)
|
||||
{
|
||||
this.move = 1;
|
||||
Object.defineProperty(this, "orientation", {
|
||||
value: orientation,
|
||||
enumerable: true
|
||||
});
|
||||
}
|
||||
|
||||
function Tail(player, sdata)
|
||||
{
|
||||
var data = {
|
||||
tail: [],
|
||||
tailGrid: [],
|
||||
prev: null,
|
||||
startRow: 0,
|
||||
startCol: 0,
|
||||
prevRow: 0,
|
||||
prevCol: 0,
|
||||
player: player
|
||||
};
|
||||
|
||||
if (sdata)
|
||||
{
|
||||
data.startRow = data.prevRow = sdata.startRow || 0;
|
||||
data.startCol = data.prevCol = sdata.startCol || 0;
|
||||
sdata.tail.forEach(function(val) {
|
||||
addTail(data, val.orientation, val.move);
|
||||
});
|
||||
}
|
||||
data.grid = player.grid;
|
||||
|
||||
defineInstanceMethods(this, data, addTail, hitsTail, fillTail, renderTail, reposition, serialData);
|
||||
Object.defineProperty(this, "moves", {
|
||||
get: function() {return data.tail.slice(0);},
|
||||
enumerable: true
|
||||
});
|
||||
}
|
||||
|
||||
//Instance methods.
|
||||
function serialData(data) {
|
||||
return {
|
||||
tail: data.tail,
|
||||
startRow: data.startRow,
|
||||
startCol: data.startCol
|
||||
};
|
||||
}
|
||||
|
||||
function setTailGrid(data, tailGrid, r, c)
|
||||
{
|
||||
if (!tailGrid[r])
|
||||
tailGrid[r] = [];
|
||||
tailGrid[r][c] = true;
|
||||
}
|
||||
|
||||
function addTail(data, orientation, count)
|
||||
{
|
||||
if (count === undefined)
|
||||
count = 1;
|
||||
if (!count || count < 0)
|
||||
return;
|
||||
|
||||
var prev = data.prev;
|
||||
var r = data.prevRow, c = data.prevCol;
|
||||
if (data.tail.length === 0)
|
||||
setTailGrid(data, data.tailGrid, r, c);
|
||||
|
||||
if (!prev || prev.orientation !== orientation)
|
||||
{
|
||||
prev = data.prev = new TailMove(orientation);
|
||||
data.tail.push(prev);
|
||||
prev.move += count - 1;
|
||||
}
|
||||
else
|
||||
prev.move += count;
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var pos = walk([data.prevRow, data.prevCol], null, orientation, 1);
|
||||
data.prevRow = pos[0];
|
||||
data.prevCol = pos[1];
|
||||
setTailGrid(data, data.tailGrid, pos[0], pos[1]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function reposition(data, row, col)
|
||||
{
|
||||
data.prevRow = data.startRow = row;
|
||||
data.prevCol = data.startCol = col;
|
||||
data.prev = null;
|
||||
if (data.tail.length === 0)
|
||||
return;
|
||||
else
|
||||
{
|
||||
var ret = data.tail;
|
||||
data.tail = [];
|
||||
data.tailGrid = [];
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
function render2(data, ctx)
|
||||
{
|
||||
ctx.fillStyle = data.player.tailColor.rgbString();
|
||||
for (var r = 0; r < data.tailGrid.length; r++)
|
||||
{
|
||||
if (!data.tailGrid[r])
|
||||
continue;
|
||||
for (var c = 0; c < data.tailGrid[r].length; c++)
|
||||
if (data.tailGrid[r][c])
|
||||
ctx.fillRect(c * CELL_WIDTH, r * CELL_WIDTH, CELL_WIDTH, CELL_WIDTH);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
//Helper methods.
|
||||
function renderTail(data, ctx)
|
||||
{
|
||||
if (data.tail.length === 0)
|
||||
return;
|
||||
|
||||
ctx.fillStyle = data.player.tailColor.rgbString();
|
||||
|
||||
var prevOrient = -1;
|
||||
var start = [data.startRow, data.startCol];
|
||||
|
||||
//fillTailRect(ctx, start, start);
|
||||
data.tail.forEach(function(tail) {
|
||||
var negDir = tail.orientation === 0 || tail.orientation === 3;
|
||||
|
||||
var back = start;
|
||||
if (!negDir)
|
||||
start = walk(start, null, tail.orientation, 1);
|
||||
var finish = walk(start, null, tail.orientation, tail.move - 1);
|
||||
|
||||
if (tail.move > 1)
|
||||
fillTailRect(ctx, start, finish);
|
||||
if (prevOrient !== -1)
|
||||
//Draw folding triangle.
|
||||
renderCorner(ctx, back, prevOrient, tail.orientation);
|
||||
|
||||
start = finish;
|
||||
if (negDir)
|
||||
walk(start, start, tail.orientation, 1);
|
||||
prevOrient = tail.orientation;
|
||||
});
|
||||
|
||||
var curOrient = data.player.currentHeading;
|
||||
if (prevOrient === curOrient)
|
||||
{
|
||||
fillTailRect(ctx, start, start);
|
||||
}
|
||||
else
|
||||
renderCorner(ctx, start, prevOrient, curOrient);
|
||||
}
|
||||
|
||||
function renderCorner(ctx, cornerStart, dir1, dir2)
|
||||
{
|
||||
if (dir1 === 0 || dir2 === 0)
|
||||
walk(cornerStart, cornerStart, 2, 1);
|
||||
if (dir1 === 3 || dir2 === 3)
|
||||
walk(cornerStart, cornerStart, 1, 1);
|
||||
|
||||
var a = walk(cornerStart, null, dir2, 1);
|
||||
var b = walk(a, null, dir1, 1);
|
||||
|
||||
var triangle = new Path2D();
|
||||
triangle.moveTo(cornerStart[1] * CELL_WIDTH, cornerStart[0] * CELL_WIDTH);
|
||||
triangle.lineTo(a[1] * CELL_WIDTH, a[0] * CELL_WIDTH);
|
||||
triangle.lineTo(b[1] * CELL_WIDTH, b[0] * CELL_WIDTH);
|
||||
triangle.closePath();
|
||||
for (var i = 0; i < 2; i++)
|
||||
ctx.fill(triangle);
|
||||
}
|
||||
|
||||
function walk(from, ret, orient, dist)
|
||||
{
|
||||
ret = ret || [];
|
||||
ret[0] = from[0];
|
||||
ret[1] = from[1];
|
||||
switch (orient)
|
||||
{
|
||||
case 0: ret[0] -= dist; break; //UP
|
||||
case 1: ret[1] += dist; break; //RIGHT
|
||||
case 2: ret[0] += dist; break; //DOWN
|
||||
case 3: ret[1] -= dist; break; //LEFT
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function fillTailRect(ctx, start, end)
|
||||
{
|
||||
var x = start[1] * CELL_WIDTH;
|
||||
var y = start[0] * CELL_WIDTH;
|
||||
var width = (end[1] - start[1]) * CELL_WIDTH;
|
||||
var height = (end[0] - start[0]) * CELL_WIDTH;
|
||||
|
||||
if (width === 0)
|
||||
width += CELL_WIDTH;
|
||||
if (height === 0)
|
||||
height += CELL_WIDTH;
|
||||
|
||||
if (width < 0)
|
||||
{
|
||||
x += width;
|
||||
width = -width;
|
||||
}
|
||||
if (height < 0)
|
||||
{
|
||||
y += height;
|
||||
height = -height;
|
||||
}
|
||||
ctx.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
function fillTail(data)
|
||||
{
|
||||
if (data.tail.length === 0)
|
||||
return;
|
||||
|
||||
function onTail(c) { return data.tailGrid[c[0]] && data.tailGrid[c[0]][c[1]]; }
|
||||
|
||||
var grid = data.grid;
|
||||
var start = [data.startRow, data.startCol];
|
||||
var been = new Grid(grid.size);
|
||||
var coords = [];
|
||||
|
||||
coords.push(start);
|
||||
while (coords.length > 0) //BFS for all tail spaces.
|
||||
{
|
||||
var coord = coords.shift();
|
||||
var r = coord[0];
|
||||
var c = coord[1];
|
||||
|
||||
if (grid.isOutOfBounds(r, c))
|
||||
continue;
|
||||
|
||||
if (been.get(r, c))
|
||||
continue;
|
||||
|
||||
if (onTail(coord)) //on the tail.
|
||||
{
|
||||
been.set(r, c, true);
|
||||
grid.set(r, c, data.player);
|
||||
|
||||
//Find all spots that this tail encloses.
|
||||
floodFill(data, grid, r + 1, c, been);
|
||||
floodFill(data, grid, r - 1, c, been);
|
||||
floodFill(data, grid, r, c + 1, been);
|
||||
floodFill(data, grid, r, c - 1, been);
|
||||
|
||||
coords.push([r + 1, c]);
|
||||
coords.push([r - 1, c]);
|
||||
coords.push([r, c + 1]);
|
||||
coords.push([r, c - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function floodFill(data, grid, row, col, been)
|
||||
{
|
||||
function onTail(c) { return data.tailGrid[c[0]] && data.tailGrid[c[0]][c[1]]; }
|
||||
|
||||
var start = [row, col];
|
||||
if (grid.isOutOfBounds(row, col) || been.get(row, col) || onTail(start) || grid.get(row, col) === data.player)
|
||||
return; //Avoid allocating too many resources.
|
||||
|
||||
var coords = [];
|
||||
var filled = new Stack(GRID_SIZE * GRID_SIZE + 1);
|
||||
var surrounded = true;
|
||||
|
||||
coords.push(start);
|
||||
while (coords.length > 0)
|
||||
{
|
||||
var coord = coords.shift();
|
||||
var r = coord[0];
|
||||
var c = coord[1];
|
||||
|
||||
if (grid.isOutOfBounds(r, c))
|
||||
{
|
||||
surrounded = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
//End this traverse on boundaries (where we been, on the tail, and when we enter our territory)
|
||||
if (been.get(r, c) || onTail(coord) || grid.get(r, c) === data.player)
|
||||
continue;
|
||||
|
||||
been.set(r, c, true);
|
||||
|
||||
if (surrounded)
|
||||
filled.push(coord);
|
||||
|
||||
coords.push([r + 1, c]);
|
||||
coords.push([r - 1, c]);
|
||||
coords.push([r, c + 1]);
|
||||
coords.push([r, c - 1]);
|
||||
}
|
||||
if (surrounded)
|
||||
{
|
||||
while (!filled.isEmpty())
|
||||
{
|
||||
coord = filled.pop();
|
||||
grid.set(coord[0], coord[1], data.player);
|
||||
}
|
||||
}
|
||||
|
||||
return surrounded;
|
||||
}
|
||||
|
||||
function hitsTail(data, other)
|
||||
{
|
||||
return (data.prevRow !== other.row || data.prevCol !== other.col) &&
|
||||
(data.startRow !== other.row || data.startCol !== other.col) &&
|
||||
!!(data.tailGrid[other.row] && data.tailGrid[other.row][other.col]);
|
||||
}
|
||||
|
||||
var SPEED = 5;
|
||||
var SHADOW_OFFSET = 10;
|
||||
|
||||
function Player(grid, sdata) {
|
||||
var data = {};
|
||||
|
||||
//Parameters
|
||||
data.num = sdata.num;
|
||||
data.name = sdata.name || ""; //|| "Player " + (data.num + 1);
|
||||
data.grid = grid;
|
||||
data.posX = sdata.posX;
|
||||
data.posY = sdata.posY;
|
||||
this.heading = data.currentHeading = sdata.currentHeading; //0 is up, 1 is right, 2 is down, 3 is left.
|
||||
data.waitLag = sdata.waitLag || 0;
|
||||
data.dead = false;
|
||||
|
||||
//Only need colors for client side.
|
||||
var base;
|
||||
if (sdata.base)
|
||||
base = this.baseColor = sdata.base instanceof Color ? sdata.base : Color.fromData(sdata.base);
|
||||
else
|
||||
{
|
||||
var hue = Math.random();
|
||||
this.baseColor = base = new Color(hue, .8, .5);
|
||||
}
|
||||
this.shadowColor = base.deriveLumination(-.3);
|
||||
this.tailColor = base.deriveLumination(.2).deriveAlpha(.5);
|
||||
|
||||
//Tail requires special handling.
|
||||
this.grid = grid; //Temporary
|
||||
if (sdata.tail)
|
||||
data.tail = new Tail(this, sdata.tail);
|
||||
else
|
||||
{
|
||||
data.tail = new Tail(this);
|
||||
data.tail.reposition(calcRow(data), calcCol(data));
|
||||
}
|
||||
|
||||
//Instance methods.
|
||||
this.move = move.bind(this, data);
|
||||
this.die = function() { data.dead = true;};
|
||||
this.serialData = function() {
|
||||
return {
|
||||
base: this.baseColor,
|
||||
num: data.num,
|
||||
name: data.name,
|
||||
posX: data.posX,
|
||||
posY: data.posY,
|
||||
currentHeading: data.currentHeading,
|
||||
tail: data.tail.serialData(),
|
||||
waitLag: data.waitLag
|
||||
};
|
||||
};
|
||||
|
||||
//Read-only Properties.
|
||||
defineAccessorProperties(this, data, "currentHeading", "dead", "name", "num", "posX", "posY", "grid", "tail", "waitLag");
|
||||
Object.defineProperties(this, {
|
||||
row: defineGetter(function() { return calcRow(data); }),
|
||||
col: defineGetter(function() { return calcCol(data); })
|
||||
});
|
||||
}
|
||||
|
||||
//Gets the next integer in positive or negative direction.
|
||||
function nearestInteger(positive, val)
|
||||
{
|
||||
return positive ? Math.ceil(val) : Math.floor(val);
|
||||
}
|
||||
|
||||
function calcRow(data)
|
||||
{
|
||||
return nearestInteger(data.currentHeading === 2 /*DOWN*/, data.posY / CELL_WIDTH);
|
||||
}
|
||||
|
||||
function calcCol(data)
|
||||
{
|
||||
return nearestInteger(data.currentHeading === 1 /*RIGHT*/, data.posX / CELL_WIDTH);
|
||||
}
|
||||
|
||||
//Instance methods
|
||||
Player.prototype.render = function(ctx, fade)
|
||||
{
|
||||
//Render tail.
|
||||
this.tail.renderTail(ctx);
|
||||
|
||||
//Render player.
|
||||
fade = fade || 1;
|
||||
ctx.fillStyle = this.shadowColor.deriveAlpha(fade).rgbString();
|
||||
ctx.fillRect(this.posX, this.posY, CELL_WIDTH, CELL_WIDTH);
|
||||
|
||||
var mid = CELL_WIDTH / 2;
|
||||
var grd = ctx.createRadialGradient(this.posX + mid, this.posY + mid - SHADOW_OFFSET, 1,
|
||||
this.posX + mid, this.posY + mid - SHADOW_OFFSET, CELL_WIDTH);
|
||||
grd.addColorStop(0, this.baseColor.deriveAlpha(fade).rgbString());
|
||||
grd.addColorStop(1, new Color(0, 0, 1, fade).rgbString());
|
||||
ctx.fillStyle = grd;
|
||||
ctx.fillRect(this.posX - 1, this.posY - SHADOW_OFFSET, CELL_WIDTH + 2, CELL_WIDTH);
|
||||
|
||||
//Render name
|
||||
ctx.fillStyle = this.shadowColor.deriveAlpha(fade).rgbString();
|
||||
ctx.textAlign = "center";
|
||||
|
||||
var yoff = -SHADOW_OFFSET * 2;
|
||||
if (this.row === 0)
|
||||
yoff = SHADOW_OFFSET * 2 + CELL_WIDTH;
|
||||
ctx.font = "18px Changa";
|
||||
ctx.fillText(this.name, this.posX + CELL_WIDTH / 2, this.posY + yoff);
|
||||
};
|
||||
|
||||
|
||||
function move(data)
|
||||
{
|
||||
if (data.waitLag < NEW_PLAYER_LAG)
|
||||
{
|
||||
data.waitLag++;
|
||||
return;
|
||||
}
|
||||
|
||||
//Move to new position.
|
||||
var heading = this.heading;
|
||||
if (this.posX % CELL_WIDTH !== 0 || this.posY % CELL_WIDTH !== 0)
|
||||
heading = data.currentHeading;
|
||||
else
|
||||
data.currentHeading = heading;
|
||||
switch (heading)
|
||||
{
|
||||
case 0: data.posY -= SPEED; break; //UP
|
||||
case 1: data.posX += SPEED; break; //RIGHT
|
||||
case 2: data.posY += SPEED; break; //DOWN
|
||||
case 3: data.posX -= SPEED; break; //LEFT
|
||||
}
|
||||
|
||||
//Check for out of bounds.
|
||||
var row = this.row, col = this.col;
|
||||
if (data.grid.isOutOfBounds(row, col))
|
||||
{
|
||||
data.dead = true;
|
||||
return;
|
||||
}
|
||||
|
||||
//Update tail position.
|
||||
if (data.grid.get(row, col) === this)
|
||||
{
|
||||
//Safe zone!
|
||||
this.tail.fillTail();
|
||||
this.tail.reposition(row, col);
|
||||
}
|
||||
//If we are completely in a new cell (not in our safe zone), we add to the tail.
|
||||
else if (this.posX % CELL_WIDTH === 0 && this.posY % CELL_WIDTH === 0)
|
||||
this.tail.addTail(heading);
|
||||
}
|
||||
|
||||
module.exports = Player;
|
||||
Binary file not shown.
@@ -1,2 +0,0 @@
|
||||
//code.stephenmorley.org
|
||||
function Queue(){var a=[],b=0;this.getLength=function(){return a.length-b};this.isEmpty=function(){return 0==a.length};this.enqueue=function(b){a.push(b)};this.dequeue=function(){if(0!=a.length){var c=a[b];2*++b>=a.length&&(a=a.slice(b),b=0);return c}};this.peek=function(){return 0<a.length?a[b]:void 0}};
|
||||
Binary file not shown.
-9707
File diff suppressed because it is too large.
Load diff
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var cachedSetTimeout,cachedClearTimeout,process=module.exports={};!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],3:[function(require,module,exports){function Color(h,s,l,a){verifyRange(h,s,l),void 0===a?a=1:verifyRange(a),Object.defineProperties(this,{hue:{value:h,enumerable:!0},sat:{value:s,enumerable:!0},lum:{value:l,enumerable:!0},alpha:{value:a,enumerable:!0}})}function verifyRange(){for(var i=0;i<arguments.length;i++)if(arguments[i]<0||arguments[i]>1)throw new RangeError("H, S, L, and A parameters must be between the range [0, 1]")}function hslToRgb(h,s,l){var r,g,b;if(0==s)r=g=b=l;else{var hue2rgb=function(p,q,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+6*(q-p)*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p},q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;r=hue2rgb(p,q,h+1/3),g=hue2rgb(p,q,h),b=hue2rgb(p,q,h-1/3)}return[Math.round(255*r),Math.round(255*g),Math.round(255*b)]}Color.fromData=function(data){return new Color(data.hue,data.sat,data.lum,data.alpha)},Color.prototype.interpolateToString=function(color,amount){for(var rgbThis=hslToRgb(this.hue,this.sat,this.lum),rgbThat=hslToRgb(color.hue,color.sat,color.lum),rgb=[],i=0;i<3;i++)rgb[i]=Math.floor((rgbThat[i]-rgbThis[i])*amount+rgbThis[i]);return{rgbString:function(){return"rgb("+rgb[0]+", "+rgb[1]+", "+rgb[2]+")"}}},Color.prototype.deriveLumination=function(amount){var lum=this.lum+amount;return lum=Math.min(Math.max(lum,0),1),new Color(this.hue,this.sat,lum,this.alpha)},Color.prototype.deriveHue=function(amount){var hue=this.hue-amount;return new Color(hue-Math.floor(hue),this.sat,this.lum,this.alpha)},Color.prototype.deriveSaturation=function(amount){var sat=this.sat+amount;return sat=Math.min(Math.max(sat,0),1),new Color(this.hue,sat,this.lum,this.alpha)},Color.prototype.deriveAlpha=function(newAlpha){return verifyRange(newAlpha),new Color(this.hue,this.sat,this.lum,newAlpha)},Color.prototype.rgbString=function(){var rgb=hslToRgb(this.hue,this.sat,this.lum);return rgb[3]=this.a,"rgba("+rgb[0]+", "+rgb[1]+", "Line truncated
|
||||
Socket.prototype.subEvents=function(){if(!this.subs){var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]}},Socket.prototype.open=Socket.prototype.connect=function(){return this.connected?this:(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting"),this)},Socket.prototype.send=function(){var args=toArray(arguments);return args.unshift("message"),this.emit.apply(this,args),this},Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev))return emit.apply(this,arguments),this;var args=toArray(arguments),parserType=parser.EVENT;hasBin(args)&&(parserType=parser.BINARY_EVENT);var packet={type:parserType,data:args};return packet.options={},packet.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof args[args.length-1]&&(debug("emitting packet with ack id %d",this.ids),this.acks[this.ids]=args.pop(),packet.id=this.ids++),this.connected?this.packet(packet):this.sendBuffer.push(packet),delete this.flags,this},Socket.prototype.packet=function(packet){packet.nsp=this.nsp,this.io.packet(packet)},Socket.prototype.onopen=function(){debug("transport is open - connecting"),"/"!==this.nsp&&(this.query?this.packet({type:parser.CONNECT,query:this.query}):this.packet({type:parser.CONNECT}))},Socket.prototype.onclose=function(reason){debug("close (%s)",reason),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",reason)},Socket.prototype.onpacket=function(packet){if(packet.nsp===this.nsp)switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data)}},Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args),null!=packet.id&&(debug("attaching ack callback to event"),args.push(this.ack(packet.id))),this.connected?emit.apply(this,args):this.receiveBuffer.push(args)},Socket.prototype.ack=function(id){var self=this,sent=!1;return function(){if(!sent){sent=!0;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}}},Socket.prototype.onack=function(packet){var ack=this.acks[packet.id];"function"==typeof ack?(debug("calling ack %s with %j",packet.id,packet.data),ack.apply(this,packet.data),delete this.acks[packet.id]):debug("bad ack %s",packet.id)},Socket.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},Socket.prototype.emitBuffered=function(){var i;for(i=0;i<this.receiveBuffer.length;i++)emit.apply(this,this.receiveBuffer[i]);for(this.receiveBuffer=[],i=0;i<this.sendBuffer.length;i++)this.packet(this.sendBuffer[i]);this.sendBuffer=[]},Socket.prototype.ondisconnect=function(){debug("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},Socket.prototype.destroy=function(){if(this.subs){for(var i=0;i<this.subs.length;i++)this.subs[i].destroy();this.subs=null}this.io.destroy(this)},Socket.prototype.close=Socket.prototype.disconnect=function(){return this.connected&&(debug("performing disconnect (%s)",this.nsp),this.packet({type:parser.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},Socket.prototype.compress=function(compress){return this.flags=this.flags||{},this.flags.compress=compress,this}},{"./on":11,"component-bind":15,"component-emitter":16,debug:17,"has-binary":42,"socket.io-parser":47,"to-array":55}],13:[function(require,module,exports){(function(global){function url(uri,loc){var obj=uri;loc=loc||global.location,null==uri&&(uri=loc.protocol+"//"+loc.host),"string"==typeof uri&&("/"===uri.charAt(0)&&(uri="/"===uri.charAt(1)?loc.protocol+uri:loc.host+uri),/^(https?|wss?):\/\//.test(uri)||(debug("protocol-less url %s",uri),uri=void 0!==loc?loc.protocol+"//"+uri:"https://"+uri),debug("parse %s",uri),obj=parseuri(uri)),obj.port||(/^(http|ws)$/.test(obj.protocol)?obj.port="80":/^(http|ws)s$/.test(obj.protocol)&&(obj.port="443")),obj.path=obj.path||"/";var ipv6=obj.host.indexOf(":")!==-1,host=ipv6?"["+obj.host+"]":obj.host;return obj.id=obj.protocol+"://"+host+":"+obj.port,obj.href=obj.protocol+"://"+host+(loc&&loc.port===obj.port?"":":"+obj.port),obj}var parseuri=require("parseuri"),debug=require("debug")("socket.io-client:url");module.exports=url}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{debug:17,parseuri:45}],14:[function(require,module,exports){function Backoff(opts){opts=opts||{},this.ms=opts.min||100,this.max=opts.max||1e4,this.factor=opts.factor||2,this.jitter=opts.jitter>0&&opts.jitter<=1?opts.jitter:0,this.attempts=0}module.exports=BackoLine truncated
|
||||
var isBinary="string"!=typeof data&&void 0!==data,req=this.request({method:"POST",data:data,isBinary:isBinary}),self=this;req.on("success",fn),req.on("error",function(err){self.onError("xhr post error",err)}),this.sendXhr=req},XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request(),self=this;req.on("data",function(data){self.onData(data)}),req.on("error",function(err){self.onError("xhr poll error",err)}),this.pollXhr=req},Emitter(Request.prototype),Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx,opts.key=this.key,opts.passphrase=this.passphrase,opts.cert=this.cert,opts.ca=this.ca,opts.ciphers=this.ciphers,opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts),self=this;try{debug("xhr open %s: %s",this.method,this.uri),xhr.open(this.method,this.uri,this.async);try{if(this.extraHeaders){xhr.setDisableHeaderCheck(!0);for(var i in this.extraHeaders)this.extraHeaders.hasOwnProperty(i)&&xhr.setRequestHeader(i,this.extraHeaders[i])}}catch(e){}if(this.supportsBinary&&(xhr.responseType="arraybuffer"),"POST"===this.method)try{this.isBinary?xhr.setRequestHeader("Content-type","application/octet-stream"):xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{xhr.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in xhr&&(xhr.withCredentials=!0),this.requestTimeout&&(xhr.timeout=this.requestTimeout),this.hasXDR()?(xhr.onload=function(){self.onLoad()},xhr.onerror=function(){self.onError(xhr.responseText)}):xhr.onreadystatechange=function(){4===xhr.readyState&&(200===xhr.status||1223===xhr.status?self.onLoad():setTimeout(function(){self.onError(xhr.status)},0))},debug("xhr data %s",this.data),xhr.send(this.data)}catch(e){return void setTimeout(function(){self.onError(e)},0)}global.document&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)},Request.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},Request.prototype.onData=function(data){this.emit("data",data),this.onSuccess()},Request.prototype.onError=function(err){this.emit("error",err),this.cleanup(!0)},Request.prototype.cleanup=function(fromError){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=empty:this.xhr.onreadystatechange=empty,fromError)try{this.xhr.abort()}catch(e){}global.document&&delete Request.requests[this.index],this.xhr=null}},Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if("application/octet-stream"===contentType)data=this.xhr.response||this.xhr.responseText;else if(this.supportsBinary)try{data=String.fromCharCode.apply(null,new Uint8Array(this.xhr.response))}catch(e){for(var ui8Arr=new Uint8Array(this.xhr.response),dataArray=[],idx=0,length=ui8Arr.length;idx<length;idx++)dataArray.push(ui8Arr[idx]);data=String.fromCharCode.apply(null,dataArray)}else data=this.xhr.responseText}catch(e){this.onError(e)}null!=data&&this.onData(data)},Request.prototype.hasXDR=function(){return void 0!==global.XDomainRequest&&!this.xs&&this.enablesXDR},Request.prototype.abort=function(){this.cleanup()},Request.requestsCount=0,Request.requests={},global.document&&(global.attachEvent?global.attachEvent("onunload",unloadHandler):global.addEventListener&&global.addEventListener("beforeunload",unloadHandler,!1))}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./polling":27,"component-emitter":16,"component-inherit":30,debug:17,"xmlhttprequest-ssl":29}],27:[function(require,module,exports){function Polling(opts){var forceBase64=opts&&opts.forceBase64;hasXHR2&&!forceBase64||(this.supportsBinary=!1),Transport.call(this,opts)}var Transport=require("../transport"),parseqs=require("parseqs"),parser=require("engine.io-parser"),inherit=require("component-inherit"),yeast=require("yeast"),debug=require("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){return null!=new(require("xmlhttprequest-ssl"))({xdomain:!1}).responseType}();inherit(Polling,Transport),Polling.prototype.name="polling",Polling.prototype.doOpen=function(){this.poll()},Polling.prototype.pause=function(onPause){function pause(){debug("paused"),self.readyState="paused",onPause()}var self=this;if(this.readyState="pausing",this.polling||!this.writable){var total=0;this.polling&&(debug("we are currently polling - waiting to pause"),total++,this.once("pollComplete",function(){debug("pre-pause polling complete"),--total||pause()})),this.writable||(debug("we are currently writing - waiting to pause"),total++,this.once("drain",function(){debug("pre-pause writing complete"),--total||pause()}))}else pause()},Polling.prototype.poll=function(){debug("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},Polling.prototype.onData=function(data){var self=this;debug("polling got
Line truncated
|
||||
containingObject?containingObject[curKey]=this.result:bloblessData=this.result,--pendingBlobs||callback(bloblessData)},fileReader.readAsArrayBuffer(obj)}else if(isArray(obj))for(var i=0;i<obj.length;i++)_removeBlobs(obj[i],i,obj);else if(obj&&"object"==typeof obj&&!isBuf(obj))for(var key in obj)_removeBlobs(obj[key],key,obj)}var pendingBlobs=0,bloblessData=data;_removeBlobs(bloblessData),pendingBlobs||callback(bloblessData)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./is-buffer":48,isarray:53}],47:[function(require,module,exports){function Encoder(){}function encodeAsString(obj){var str="",nsp=!1;return str+=obj.type,exports.BINARY_EVENT!=obj.type&&exports.BINARY_ACK!=obj.type||(str+=obj.attachments,str+="-"),obj.nsp&&"/"!=obj.nsp&&(nsp=!0,str+=obj.nsp),null!=obj.id&&(nsp&&(str+=",",nsp=!1),str+=obj.id),null!=obj.data&&(nsp&&(str+=","),str+=json.stringify(obj.data)),debug("encoded %j as %s",obj,str),str}function encodeAsBinary(obj,callback){function writeEncoding(bloblessData){var deconstruction=binary.deconstructPacket(bloblessData),pack=encodeAsString(deconstruction.packet),buffers=deconstruction.buffers;buffers.unshift(pack),callback(buffers)}binary.removeBlobs(obj,writeEncoding)}function Decoder(){this.reconstructor=null}function decodeString(str){var p={},i=0;if(p.type=Number(str.charAt(0)),null==exports.types[p.type])return error();if(exports.BINARY_EVENT==p.type||exports.BINARY_ACK==p.type){for(var buf="";"-"!=str.charAt(++i)&&(buf+=str.charAt(i),i!=str.length););if(buf!=Number(buf)||"-"!=str.charAt(i))throw new Error("Illegal attachments");p.attachments=Number(buf)}if("/"==str.charAt(i+1))for(p.nsp="";++i;){var c=str.charAt(i);if(","==c)break;if(p.nsp+=c,i==str.length)break}else p.nsp="/";var next=str.charAt(i+1);if(""!==next&&Number(next)==next){for(p.id="";++i;){var c=str.charAt(i);if(null==c||Number(c)!=c){--i;break}if(p.id+=str.charAt(i),i==str.length)break}p.id=Number(p.id)}return str.charAt(++i)&&(p=tryParse(p,str.substr(i))),debug("decoded %s as %j",str,p),p}function tryParse(p,str){try{p.data=json.parse(str)}catch(e){return error()}return p}function BinaryReconstructor(packet){this.reconPack=packet,this.buffers=[]}function error(data){return{type:exports.ERROR,data:"parser error"}}var debug=require("debug")("socket.io-parser"),json=require("json3"),Emitter=require("component-emitter"),binary=require("./binary"),isBuf=require("./is-buffer");exports.protocol=4,exports.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],exports.CONNECT=0,exports.DISCONNECT=1,exports.EVENT=2,exports.ACK=3,exports.ERROR=4,exports.BINARY_EVENT=5,exports.BINARY_ACK=6,exports.Encoder=Encoder,exports.Decoder=Decoder,Encoder.prototype.encode=function(obj,callback){if(debug("encoding packet %j",obj),exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type)encodeAsBinary(obj,callback);else{callback([encodeAsString(obj)])}},Emitter(Decoder.prototype),Decoder.prototype.add=function(obj){var packet;if("string"==typeof obj)packet=decodeString(obj),exports.BINARY_EVENT==packet.type||exports.BINARY_ACK==packet.type?(this.reconstructor=new BinaryReconstructor(packet),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",packet)):this.emit("decoded",packet);else{if(!isBuf(obj)&&!obj.base64)throw new Error("Unknown type: "+obj);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(packet=this.reconstructor.takeBinaryData(obj))&&(this.reconstructor=null,this.emit("decoded",packet))}},Decoder.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},BinaryReconstructor.prototype.takeBinaryData=function(binData){if(this.buffers.push(binData),this.buffers.length==this.reconPack.attachments){var packet=binary.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),packet}return null},BinaryReconstructor.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},{"./binary":46,"./is-buffer":48,"component-emitter":49,debug:50,json3:54}],48:[function(require,module,exports){(function(global){function isBuf(obj){return global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer}module.exports=isBuf}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],49:[function(require,module,exports){function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype)obj[key]=Emitter.prototype[key];return obj}module.exports=Emitter,Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){return this._callbacks=this._callbacks||{},(this._callbacks[event]=this._callbacks[event]||[]).push(fn),this},Emitter.prototype.once=function(event,fn){function on(){self.off(event,on),fn.apply(this,arguments)}var self=this;return this._callbacks=this._callbacks||{},on.fn=fn,this.onLine truncated
|
||||
;break;case 3:data.posX-=5}var row=this.row,col=this.col;if(data.grid.isOutOfBounds(row,col))return void(data.dead=!0);data.grid.get(row,col)===this?(this.tail.fillTail(),this.tail.reposition(row,col)):this.posX%CELL_WIDTH==0&&this.posY%CELL_WIDTH==0&&this.tail.addTail(heading)}var Stack=require("./stack.js"),Color=require("./color.js"),Grid=require("./grid.js"),consts=require("./game-consts.js"),GRID_SIZE=consts.GRID_SIZE,CELL_WIDTH=consts.CELL_WIDTH;Player.prototype.render=function(ctx,fade){this.tail.renderTail(ctx),fade=fade||1,ctx.fillStyle=this.shadowColor.deriveAlpha(fade).rgbString(),ctx.fillRect(this.posX,this.posY,CELL_WIDTH,CELL_WIDTH);var mid=CELL_WIDTH/2,grd=ctx.createRadialGradient(this.posX+mid,this.posY+mid-10,1,this.posX+mid,this.posY+mid-10,CELL_WIDTH);grd.addColorStop(0,this.baseColor.deriveAlpha(fade).rgbString()),grd.addColorStop(1,new Color(0,0,1,fade).rgbString()),ctx.fillStyle=grd,ctx.fillRect(this.posX-1,this.posY-10,CELL_WIDTH+2,CELL_WIDTH),ctx.fillStyle=this.shadowColor.deriveAlpha(fade).rgbString(),ctx.textAlign="center";var yoff=-20;0===this.row&&(yoff=20+CELL_WIDTH),ctx.font="18px Changa",ctx.fillText(this.name,this.posX+CELL_WIDTH/2,this.posY+yoff)},module.exports=Player},{"./color.js":3,"./game-consts.js":5,"./grid.js":8,"./stack.js":58}],57:[function(require,module,exports){function Rolling(value,frames){var lag=0;frames||(frames=24),this.value=value,Object.defineProperty(this,"lag",{get:function(){return lag},enumerable:!0}),this.update=function(){var delta=this.value-lag,dir=Math.sign(delta),speed=Math.abs(delta)/frames;return lag+=Math.min(Math.abs(speed),Math.abs(delta))*dir}}module.exports=Rolling},{}],58:[function(require,module,exports){function Stack(initSize){var len=0,arr=[];this.ensureCapacity=function(size){arr.length=Math.max(arr.length,size||0)},this.push=function(ele){this[len]=ele,len++},this.pop=function(){if(0!==len){len--;var tmp=this[len];return this[len]=void 0,tmp}},this.isEmpty=function(){return 0===len},this.ensureCapacity(initSize),Object.defineProperty(this,"length",{get:function(){return len}})}module.exports=Stack},{}]},{},[4]);
|
||||
@@ -1,24 +0,0 @@
|
||||
/* arabic */
|
||||
@font-face {
|
||||
font-family: 'Changa';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
src: local('Changa SemiBold'), local('Changa-SemiBold'), url(8-mw6umTgtMSI5PXqVIDMRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
|
||||
unicode-range: U+0600-06FF, U+200C-200E, U+2010-2011, U+FB50-FDFF, U+FE80-FEFC;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Changa';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
src: local('Changa SemiBold'), local('Changa-SemiBold'), url(l9R1mHXzJ6oxjfw8BkQIThJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Changa';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
src: local('Changa SemiBold'), local('Changa-SemiBold'), url(aXdbZDB08TCIBRKa7Qgu_FtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
<head>
|
||||
<meta name=viewport content="width=device-width, initial-scale=1">
|
||||
<link href="changa.css" rel="stylesheet">
|
||||
<link href="styles.css" rel="stylesheet">
|
||||
<script src="jquery.min.js"></script>
|
||||
<script src="bundle.min.js"></script>
|
||||
<title>Blockly.IO</title>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="main-ui"></canvas>
|
||||
<div id="stats" style="opacity: 0" class="fullscreen hidden">
|
||||
<div style="padding-top: 100px"></div>
|
||||
<div class="card">
|
||||
<h1 id="score">Score: <span id="score-num">0</span></h1>
|
||||
<h1 id="high-score">High Score: <span id="high-score-num">0</span></h1>
|
||||
<h1 id="time">Time Alive: <span id="time-num">0</span></h1>
|
||||
<h1 id="killed">Killed: <span id="killed-num">0</span></h1>
|
||||
</div>
|
||||
</div>
|
||||
<div id="begin" style="opacity: .99999" class="fullscreen">
|
||||
<div class="center">
|
||||
<h1>Blockly.IO!</h1>
|
||||
<small>Todo: replace ^^^ with a picture. Work in progress.</small><br>
|
||||
|
||||
<h1>Enter your name</h1>
|
||||
<div>
|
||||
<input autocomplete="off" id="name" placeholder="An awesome name!">
|
||||
</div>
|
||||
<div class="blockless">
|
||||
<button type="submit">Play!</button>
|
||||
</div>
|
||||
<div class="blockless">
|
||||
<small id="error">Your browser does not support JavaScript!</small>
|
||||
</div>
|
||||
<br>
|
||||
<small>Visit the open-source code on <a href="https://github.com/theKidOfArcrania/PaperIO-Web">GitHub</a>!</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
Vendored
-4
@@ -1,4 +0,0 @@
|
||||
/*! jQuery v3.1.1 | (c) jQuery Foundation | jquery.org/license */
|
||||
!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.1.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=r.isArray(d)))?(e?(e=!1,f=c&&r.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+Line truncated
|
||||
a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},T=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function U(){this.expando=r.expando+U.uid++}U.uid=1,U.prototype={cache:function(a){var b=a[this.expando];return b||(b={},T(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){r.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(K)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var V=new U,W=new U,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Y=/[A-Z]/g;function Z(a){return"true"===a||"false"!==a&&("null"===a?null:a===+a+""?+a:X.test(a)?JSON.parse(a):a)}function $(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Y,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c=Z(c)}catch(e){}W.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return W.hasData(a)||V.hasData(a)},data:function(a,b,c){return W.access(a,b,c)},removeData:function(a,b){W.remove(a,b)},_data:function(a,b,c){return V.access(a,b,c)},_removeData:function(a,b){V.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=W.get(f),1===f.nodeType&&!V.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),$(f,d,e[d])));V.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){W.set(this,a)}):S(this,function(b){var c;if(f&&void 0===b){if(c=W.get(f,a),void 0!==c)return c;if(c=$(f,a),void 0!==c)return c}else this.each(function(){W.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=V.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var _=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,aa=new RegExp("^(?:([+-])=|)("+_+")([a-z%]*)$","i"),ba=["Top","Right","Bottom","Left"],ca=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function ea(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&aa.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var fa={};function ga(a){var b,c=a.ownerDocument,d=a.nodeName,e=fa[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),fLine truncated
|
||||
void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),ib={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=jb[b]||r.find.attr;jb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=jb[g],jb[g]=e,e=null!=c(a,b,d)?g:null,jb[g]=f),e}});var kb=/^(?:input|select|textarea|button)$/i,lb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):kb.test(a.nodeName)||lb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function mb(a){var b=a.match(K)||[];return b.join(" ")}function nb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,nb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,nb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,nb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=nb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(nb(c))+" ").indexOf(b)>-1)return!0;return!1}});var ob=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(ob,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:mb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d<i;d++)if(c=e[d],(c.selected||d===f)&&!c.disabled&&(!c.parentNode.disabled||!r.nodeName(c.parentNode,"optgroup"))){if(b=r(c).val(),g)return b;h.push(b)}return h},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[Line truncated
|
||||
Binary file not shown.
@@ -1,79 +0,0 @@
|
||||
body, html {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
background: black;
|
||||
|
||||
color: white;
|
||||
font-family: "Changa", "Sans Serif";
|
||||
}
|
||||
#error {
|
||||
color: red;
|
||||
}
|
||||
|
||||
canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.fullscreen {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: black;
|
||||
}
|
||||
|
||||
.center {
|
||||
vertical-align: middle;
|
||||
text-align: center;
|
||||
margin: 1rem;
|
||||
margin-top: 0rem;
|
||||
padding-top: 3rem;
|
||||
}
|
||||
|
||||
input {
|
||||
font-family: "Changa", "Sans Serif";
|
||||
font-size: 24px;
|
||||
padding: .5rem 1rem;
|
||||
border: 4px solid lightgray;
|
||||
border-radius: 2px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
button {
|
||||
border-style: solid;
|
||||
border-color: #e6e699 #b8b814 #b8b814 #e6e699;
|
||||
border-width: 4px 4px 4px 4px;
|
||||
border-radius: 4px;
|
||||
background: #eded5e;
|
||||
font-family: "Changa", "Sans-serif";
|
||||
font-size: 24px;
|
||||
padding: .5rem 1rem;
|
||||
width: 100%;
|
||||
margin-top: .5rem;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 769px){
|
||||
button, input {
|
||||
width: 50%;
|
||||
}
|
||||
}
|
||||
|
||||
button:active {
|
||||
border-color: #73730d #cccc7d #cccc7d #73730d;
|
||||
background: #e8e830;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#stats
|
||||
{
|
||||
background: rgb(80, 80, 80);
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
<script src="socket.io.min.js"></script>
|
||||
<script src="socket-test.js"></script>
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
|
||||
function Rolling(value, frames)
|
||||
{
|
||||
var lag = 0;
|
||||
|
||||
if (!frames)
|
||||
frames = 24;
|
||||
|
||||
this.value = value;
|
||||
|
||||
Object.defineProperty(this, "lag", {
|
||||
get: function() { return lag; },
|
||||
enumerable: true
|
||||
});
|
||||
this.update = function() {
|
||||
var delta = this.value - lag;
|
||||
var dir = Math.sign(delta);
|
||||
var speed = Math.abs(delta) / frames;
|
||||
var mag = Math.min(Math.abs(speed), Math.abs(delta));
|
||||
|
||||
lag += mag * dir;
|
||||
return lag;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Rolling;
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
//TODO: rename as "blockly.io".
|
||||
var hostname = process.argv[2] || "0.0.0.0";
|
||||
var port = parseInt(process.argv[3]) || 80;
|
||||
|
||||
var express = require('express');
|
||||
var compression = require('compression')
|
||||
var app = express();
|
||||
|
||||
//Create static server
|
||||
app.use(compression());
|
||||
app.use(express.static('public'));
|
||||
app.listen(port, hostname);
|
||||
|
||||
var http = require('http');
|
||||
var server = http.createServer();
|
||||
var io = require('socket.io')(server);
|
||||
io.set('transports', ['websocket']);
|
||||
|
||||
var Game = require('./game-server.js');
|
||||
var games = [new Game()];
|
||||
io.on('connection', function(socket){
|
||||
socket.on("hello", function(data, fn) {
|
||||
//TODO: error checking.
|
||||
if (data.name && data.name.length > 32)
|
||||
fn(false, "Your name is too long!");
|
||||
else if (!games[0].addPlayer(socket, data.name))
|
||||
fn(false, "Game is too full!");
|
||||
else
|
||||
fn(true);
|
||||
});
|
||||
socket.on("checkConn", function(fn) { fn(); });
|
||||
});
|
||||
server.listen(8081);
|
||||
|
||||
function tick() {
|
||||
games[0].tickFrame();
|
||||
setTimeout(tick, 1000 / 60);
|
||||
}
|
||||
tick();
|
||||
//setTimeout(tick, 1000 / 60);
|
||||
@@ -1,13 +0,0 @@
|
||||
var ws = require("nodejs-websocket")
|
||||
|
||||
// Scream server example: "hi" -> "HI!!!"
|
||||
var server = ws.createServer(function (conn) {
|
||||
console.log("New connection")
|
||||
conn.on("text", function (str) {
|
||||
console.log("Received "+str)
|
||||
conn.sendText(str.toUpperCase()+"!!!")
|
||||
})
|
||||
conn.on("close", function (code, reason) {
|
||||
console.log("Connection closed")
|
||||
})
|
||||
}).listen(8081);
|
||||
@@ -1,41 +0,0 @@
|
||||
|
||||
|
||||
function Stack(initSize)
|
||||
{
|
||||
var len = 0;
|
||||
var arr = [];
|
||||
|
||||
this.ensureCapacity = function(size)
|
||||
{
|
||||
arr.length = Math.max(arr.length, size || 0);
|
||||
};
|
||||
|
||||
this.push = function(ele)
|
||||
{
|
||||
this[len] = ele;
|
||||
len++;
|
||||
};
|
||||
|
||||
this.pop = function()
|
||||
{
|
||||
if (len === 0)
|
||||
return;
|
||||
len--;
|
||||
var tmp = this[len];
|
||||
this[len] = undefined;
|
||||
return tmp;
|
||||
};
|
||||
|
||||
this.isEmpty = function() {
|
||||
return len === 0;
|
||||
}
|
||||
|
||||
this.ensureCapacity(initSize);
|
||||
|
||||
|
||||
Object.defineProperty(this, "length", {
|
||||
get: function() {return len;}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = Stack;
|
||||
Reference in new issue
Block a user