How to make 2 websites to speak to each other - javascript

I'm have 2 websites hosted on localhost with different ports and I'm trying to make first one only to send data and second one only to receive that data. Earlier, I made that happens with only one website. User could login, and logged users could change data and that data would be emitted to all other users. Users which aren't logged could just view page. But there were so many problems. Taking that a part would fix some problems. I'm trying to do all this without back-end experience and knowledge just watching some videos and pasting code, and I'm sorry about that, I know this is wrong. I figured out some things but I can't make it work. So here is my terrible code:
This is node.js code for website which will send data
var express = require("express");
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);
function newConnection(socket)
{
console.log('Connection: ' + socket.id);
socket.on('data', dataMsg);
function dataMsg(data)
{
socket.broadcast.emit('data', data);
}
}
This is javascript code for website which will send data which works fine
Btw functions press1(), press2() etc. are called from html by clicking certain buttons
let ps = 2.5;
let bl = 3.5;
const socket = io('http://localhost:3000');
function update(data)
{
buttons[0].time = data.btn11;
buttons[0].price = data.btn12;
buttons[1].time = data.btn21;
buttons[1].price = data.btn22;
buttons[2].time = data.btn31;
buttons[2].price = data.btn32;
buttons[3].time = data.btn41;
buttons[3].price = data.btn42;
}
let buttons = [];
buttons[0] = new Button(ps);
buttons[1] = new Button(ps);
buttons[2] = new Button(ps);
buttons[3] = new Button(bl);
let arr = [];
arr[0] = [document.getElementById("prviprvi"), document.getElementById('prvidrugi')];
arr[1] = [document.getElementById('drugiprvi'), document.getElementById('drugidrugi')];
arr[2] = [document.getElementById('treciprvi'), document.getElementById('trecidrugi')];
arr[3] = [document.getElementById('cetvrtiprvi'), document.getElementById('cetvrtidrugi')];
var tempD = setInterval( () => {
var data = {
btn11 : buttons[0].time,
btn12 : buttons[0].price,
btn21 : buttons[1].time,
btn22 : buttons[1].price,
btn31 : buttons[2].time,
btn32 : buttons[2].price,
btn41 : buttons[3].time,
btn42 : buttons[3].price
}
socket.emit("data", data);
for(var i = 0; i < 4; i++)
{
buttons[i].update();
buttons[i].show(arr[i][0], arr[i][1]);
}
},100);
function press1()
{
buttons[0].press();
}
function press2()
{
buttons[1].press();
}
function press3()
{
buttons[2].press();
}
function press4()
{
buttons[3].press();
}
function Button(tempD1)
{
this.val = tempD1;
this.pressed = false;
this.startingTime = Date.now();
this.endingTime = Date.now();
this.hours = 0;
this.min = 0;
this.sec = 0;
this.price = 0;
this.time = "0:0:0";
this.show = function(span1, span2)
{
span1.innerHTML = this.time;
span2.innerHTML = this.price + " Din";
}
this.update = function()
{
if(this.pressed)
{
this.endingTime = Date.now();
this.tempD = this.endingTime - this.startingTime;
this.sec = parseInt((this.tempD / 1000) % 60);
this.min = parseInt(((this.tempD / 1000) / 60) % 60);
this.hours = parseInt((((this.tempD / 1000) / 60) / 60) % 24);
this.time = this.hours + ":" + this.min + ":" + this.sec;
this.price = this.hours * 60 * this.val + this.min * this.val;
}
}
this.press = function()
{
if(this.pressed == false)
{
this.startingTime = Date.now();
this.pressed = true;
}
else
{
this.pressed = false;
}
}
}
This is node.js for website which receiving data
var express = require("express");
var app = express();
var server = app.listen(3001);
app.use(express.static('public'));
var socket = require("socket.io");
var io = socket('localhost:3000');
io.sockets.on('connection', newConnection);
function newConnection(socket)
{
console.log('Connection: ' + socket.id);
socket.on('data', dataMsg);
function dataMsg(data)
{
socket.broadcast.emit('data', data);
}
}
This is javascript code for website which receiving data
let ps = 2.5;
let bl = 3.5;
const socket = io('http://localhost:3000');
socket.on('data', update);
function update(data)
{
buttons[0].time = data.btn11;
buttons[0].price = data.btn12;
buttons[1].time = data.btn21;
buttons[1].price = data.btn22;
buttons[2].time = data.btn31;
buttons[2].price = data.btn32;
buttons[3].time = data.btn41;
buttons[3].price = data.btn42;
}
var tempD = setInterval( () => {
for(var i = 0; i < 4; i++)
buttons[i].show(arr[i][0], arr[i][1]);
}
let buttons = [];
buttons[0] = new Button(ps);
buttons[1] = new Button(ps);
buttons[2] = new Button(ps);
buttons[3] = new Button(bl);
let arr = [];
arr[0] = [document.getElementById("prviprvi"), document.getElementById('prvidrugi')];
arr[1] = [document.getElementById('drugiprvi'), document.getElementById('drugidrugi')];
arr[2] = [document.getElementById('treciprvi'), document.getElementById('trecidrugi')];
arr[3] = [document.getElementById('cetvrtiprvi'), document.getElementById('cetvrtidrugi')];
function Button(tempD1)
{
this.val = tempD1;
this.pressed = false;
this.startingTime = Date.now();
this.endingTime = Date.now();
this.hours = 0;
this.min = 0;
this.sec = 0;
this.price = 0;
this.time = "0:0:0";
this.show = function(span1, span2)
{
span1.innerHTML = this.time;
span2.innerHTML = this.price + " Din";
}
this.update = function()
{
if(this.pressed)
{
this.endingTime = Date.now();
this.tempD = this.endingTime - this.startingTime;
this.sec = parseInt((this.tempD / 1000) % 60);
this.min = parseInt(((this.tempD / 1000) / 60) % 60);
this.hours = parseInt((((this.tempD / 1000) / 60) / 60) % 24);
this.time = this.hours + ":" + this.min + ":" + this.sec;
this.price = this.hours * 60 * this.val + this.min * this.val;
}
}
this.press = function()
{
if(this.pressed == false)
{
this.startingTime = Date.now();
this.pressed = true;
}
else
{
this.pressed = false;
}
}
}
Asking this may be too much but I will do it anyway:
How to allow access to the one which sends data with just the right password.
When user go to website he will be asked for password and if he type right one, he will be forwarded further. I did it last time in javascript but anyone could just go to inspect elements and see password
Thank you!

Related

Cannot get content of div to store locally and load locally

I have a JS function to save and load content of a notepad I've made, locally.
I tried to replicate this for a div which contains times of a stopwatch.(see code below)
The stopwatch when paused will write it's time to this div to be saved, I want these times to save when I refresh / close and reopen the page.
It works for my notes in the notepad, please can someone explain where I'm going wrong?
JavaScript for save function:
//Storage of Text-Box
const notesInput = document.querySelector('#notes');
function remFunc() {
// store the entered name in web storage
localStorage.setItem('notes', notes.value);
}
function loadfunc() {
if(localStorage.getItem('notes')) {
let notes_var = localStorage.getItem('notes');
notes.value= notes_var;
} else {
}
}
document.body.onload = loadfunc();
//Storage of Times DIV
const output = document.querySelector('#output');
function remfunc2() {
localStorage.setItem('output', outContent.innerHTML);
}
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
output.innerHTML = output_var ;
} else {
}
}
document.body.onload = loadfunc2();
This is the div:
<div id="output" name="output" class="buttonZ logPad"></div>
Here is the stopwatch Javascript:
// Timer JS
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
function startstop()
{
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(flagclock==0)
{
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
}
else
{
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
logTime();
}
}
function counter(starttime)
{
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if(flagstop == 1)
{
timediff = timediff + stoptime
}
if(flagclock == 1)
{
clock.innerHTML = formattime(timediff,'');
clock.setAttribute('value', formattime(timediff, ''));
refresh = setTimeout('counter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime,roundtype)
{
if(roundtype == 'round')
{
var ds = Math.round(rawtime/100) + '';
}
else
{
var ds = Math.floor(rawtime/100) + '';
}
var sec = Math.floor(rawtime/1000);
var min = Math.floor(rawtime/60000);
ds = ds.charAt(ds.length - 1);
if(min >= 60)
{
startstop();
}
sec = sec - 60 * min + '';
if(sec.charAt(sec.length - 2) != '')
{
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
}
else
{
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if(min.charAt(min.length - 2) != '')
{
min = min.charAt(min.length - 2)+min.charAt(min.length - 1);
}
else
{
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
function resetclock()
{
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
if(flagclock !== 0) {
startstopbutton.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
if(flagclock == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
}
else
{
clock.innerHTML = "00:00:0";
}
}
//Split function
function splittime()
{
if(flagclock == 1)
{
if(splitdate != '')
{
var splitold = splitdate.split(':');
var splitnow = clock.innerHTML.split(':');
var numbers = new Array();
var i = 0
for(i;i<splitold.length;i++)
{
numbers[i] = new Array();
numbers[i][0] = splitold[i]*1;
numbers[i][1] = splitnow[i]*1;
}
if(numbers[1][1] < numbers[1][0])
{
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if(numbers[2][1] < numbers[2][0])
{
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
}
splitdate = clock.innerHTML;
output.innerHTML += (++splitcounter) + '. ' + clock.innerHTML + '\n';
}
}
function logTime() {
const time = document.getElementById('clock').getAttribute('value');
document.getElementById('output').innerHTML += (++splitcounter) + '. ' + time + '<br />';
}
function time() {
splittime();
resetclock();
}
Any help will be much appreciated! Thank you.
Okay, so I figured out what I was doing wrong.
The 'output' variable was being used in the timer code.
This prevented me from setting the variable correctly.
I changed the id for the div and the variable name i was using.
I ran this code in my console on this page and it is working:
let counter = 0;
const outContent = document.querySelector('#notify-container');
setInterval(function()
{
counter++;
outContent.innerHTML = `${counter*2} seconds`;
localStorage.setItem('output', outContent.innerHTML);
}, 2000);
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
outContent.innerHTML = output_var ;
counter = parseInt(outContent.innerHTML.split(' ')[0], 10)
}
}
loadfunc2()
Paste it into the console, run it, leave it for a few seconds, then refresh the page, paste it and run it again. You can see it working.

In stuck mode to try and create a loop for my products in HTML

I have nearly finished with my project but now stuck on the hardest challenge - create a loop. I am not sure maybe map is the right method to do this. Basically, I have created a 3D can that rotates clockwise that shows the user of the can in full detail. When the cursor hovers the can, the can doubles the size and displays in front of the screen, again to see it in much better detail. Because there are different colour cans for different types of flavours, I need to create a loop and avoid DRY. However, I am struggling to do this.
I am not asking for someone to do this for me but someone to say look at these methods or try this out and see if it works differently etc…
https://codepen.io/Rosstopherrr/pen/GVRvxJ
This is my code. Hopefully, when you look at it you understand what I am. I have a 3D can on display, in an active slider but the next number of slides are empty. This is where I want to fill in the gaps for different cans - that will slide to the left, and if the cursor hovers the can it will display front of the screen.
Just really asking for advice on what to do next, what problems I should be looking at, etc. I’ve been struggling for a week now trying to create a loop but finding it impossible
$("#products>article").on("click", function(){
$("#products>article").removeClass("active");
$(this).addClass("active");
animate();
});
function getActiveArticle(){
var x = 0;
$("#products>article").each(function(e){
if($("#products>article").eq(e).hasClass("active")){
x = e;
return false;
}
});
return x;
}
function gofwd(){
var activeIndex = getActiveArticle();
var minArticles = 0;
var maxArticles = $("#products>article").length - 1;
if(activeIndex >= maxArticles){
activeIndex = minArticles-1;
}
$("#products>article").removeClass("active");
$("#products>article").eq(activeIndex+1).addClass("active");
animate();
}
function gobwd(){
var activeIndex = getActiveArticle();
var minArticles = 1;
var maxArticles = $("#products>article").length;
$("#products>article").removeClass("active");
$("#products>article").eq(activeIndex-1).addClass("active");
animate();
}
$(document).ready(function(){
animate();
});
function animate(){
var articleIndex = getActiveArticle();
var totalMargin = 25 * (articleIndex+1) - (25*(articleIndex));
var articlePosition = Math.floor($("#products>article").eq(articleIndex).offset().left - $("#products").offset().left) - totalMargin;
var productsHalfWidth = $("#products").width()/2;
if(articleIndex == 0){
var halfWidth = 150;
}else{
var halfWidth = 100;
}
var finalPosition = productsHalfWidth - articlePosition - halfWidth;
$("#products").animate({
"left": finalPosition,
}, {
duration: 500,
easing: 'easeOutBack',
});
}
$(window).on("resize", function(){
animate();
});
var autoPlay = setInterval(function(){
gofwd();
}, 3500);
$("#slider").on("mouseenter", function(){
clearInterval(autoPlay);
});
$("#slider").on("mouseleave", function(){
autoPlay = setInterval(function(){
gofwd();
}, 4500);
});
const getElement = (selector) => document.querySelector(selector);
const createElement = (tag) => document.createElement(tag);
// const addBackground1 = document.style['background'] = 'url ("https://i.postimg.cc/BZ8rj2NM/sleve.png")';
const addSideStyle = ($side, i) => {
let deg = 3.75 * i;
let bgPosition = 972 - (i * 10.125);
$side.style['background-position'] = bgPosition + 'px 0';
$side.style['-webkit-transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
$side.style['-moz-transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
$side.style['transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
};
const createBottle = () => {
const $bottle = createElement('div');
$bottle.classList.add('bottle');
const $bottleLabel = createBottleLabel();
for (let i = 0; i < 96; i = i + 1){
let $bottleSide = createBottleSide(i);
$bottleLabel.append($bottleSide);
}
$bottle.append($bottleLabel);
return $bottle;
};
const createBottleLabel = () => {
const $bottleLabel = createElement('div');
$bottleLabel.classList.add('label');
return $bottleLabel;
}
const createBottleSide = (i) => {
const $bottleSide = createElement('div');
$bottleSide.classList.add('side');
addSideStyle($bottleSide, i);
return $bottleSide;
};
const changeBottleSize = (clickFn) => {
const _bottle = createElement('div');
_bottle.classList.add('bottle');
_bottle.style['transform'] = 'scale(0.9)';
return _bottle;
}
const moveBottle = (moveFn) => {
const _moveBottle = createElement('div');
_moveBottle.classList.add('bottle');
_moveBottle.style['left'] = "-1000px";
return _moveBottle;
}
const clickFn = () => {
const $bottleSize = getElement('.container');
const $bottle1 = changeBottleSize();
const $bottle2 = changeBottleSize();
const $bottle3 = changeBottleSize();
$bottleSize.style['transform'] = 'scale(0.9)';
return $bottleSize;
}
const moveFn = () => {
const $bottleMove = getElement('.container');
const $move1 = moveBottle();
$bottleMove.style['left'] = "-1000px";
return $bottleMove;
}
const initApp = () => {
const $container = getElement('.container');
const $bottle1 = createBottle();
const $bottle2 = createBottle();
const $bottle3 = createBottle();
[$bottle1, $bottle2, $bottle3].forEach(($bottle, i) => {
$bottle.classList.add('bottle' + i);
});
$container.append($bottle1, $bottle2, $bottle3);
};
initApp();

Randomly generate enemies faster and faster Javascript

Hey I am using a Spawn function I found for a javascript game I am creating to randomy generate enemies to click on. But it is very slow and I would like it to be able to generate faster and faster.. is it possible to modify this code in that way? the spawn function is at the end of the code.
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 0.5);
gems[1] = new Gem('blue', 20, 0.4);
gems[2] = new Gem('red', 50, 0.6);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
if (target.className.indexOf('red') > 0){
var audio = new Audio('music/scream.mp3');
audio.play();
endGame("You lose");
}
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
function Stop(interval) {
clearInterval(interval);
}
function endGame( msg ) {
count = 0;
Stop(interval);
Stop(counter);
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
time.innerHTML = msg || "Game Over!";
start.style.display = "block";
UpdateScore();
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
interval = setInterval(Spawn, 750);
count = 4000;
counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
endGame();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
JS/HTML Performance tips:
1) var gems = new Array(); change to new Array(3);
2) cache all new Audio('...');
3) use getElementById it faster then querySelector('#')
4) prepare var fragment = document.createElement('span'); and cache it, use cloneNode to insert it.
5) fragment.style.left & top change to CSS3 transform: translate(). CSS3 transform use your video card GPU, style.left use CPU...
6) Use only single setInterval and run on all list of fragments.
7) You can make a pool of "fragments" and just show\hide, it will increase performance dramatically.
Basically it works slow due to many page redraws, every time you add new elements to page browser must to redraw whole screen, do not add elements, just show\hide them.

Multiplayer coins

Having a slight issue getting some coins to generate multiplayer using eureca.io websockets. I've got the players working multiplayer and from remote connections but I can't seem to get the coins to generate across the connection so they appear in the same place on all the players connections. I'm using phaser to generate the game and eureca and engine for my web connection. I've got the coins to spawn on the page with no problems, but whenever a new player joins, the coin always displays in a different place, I wondering how I can make them generate across the connection. My game code is below:
Game Code
var myId = 0;
var background;
var blueSquare;
var player;
var coins;
var goldCoin;
var squareList;
var coinList;
var cursors;
var score;
var highScore;
var ready = false;
var eurecaServer;
var eurecaClientSetup = function () {
var eurecaClient = new Eureca.Client();
eurecaClient.ready(function (proxy) {
eurecaServer = proxy;
});
eurecaClient.exports.setId = function (id)
{
myId = id;
create();
eurecaServer.handshake();
ready = true;
}
eurecaClient.exports.kill = function (id)
{
if (squareList[id]) {
squareList[id].kill();
console.log('Player has left the game ', id, squareList[id]);
}
}
eurecaClient.exports.spawnBlueSquare = function (i, x, y)
{
if (i == myId) return;
console.log('A new player has joined the game');
var blsq = new BlueSquare(i, game, blueSquare);
squareList[i] = blsq;
}
eurecaClient.exports.spawnCoins = function (c, x, y)
{
console.log('A coin has been generated');
var cn = new GenerateCoin(c, game, coin);
coinList[c] = cn;
}
eurecaClient.exports.updateState = function (id, state)
{
if (squareList[id]) {
squareList[id].cursor = state;
squareList[id].blueSquare.x = state.x;
squareList[id].blueSquare.y = state.y;
squareList[id].blueSquare.angle = state.angle;
squareList[id].update();
coinList.cursor = state;
coinList.blueSquare.x = state.x;
coinList.blueSquare.y = state.y;
coinList.update();
}
}
}
BlueSquare = function (index, game, player) {
this.cursor = {
left:false,
right:false,
up:false,
down:false,
}
this.input = {
left:false,
right:false,
up:false,
down:false,
}
var x = 0;
var y = 0;
this.game = game;
this.player = player;
this.currentSpeed = 0;
this.isBlue = true;
this.blueSquare = game.add.sprite(x, y, 'blueSquare');
this.blueSquare.anchor.set(0.5);
this.blueSquare.id = index;
game.physics.enable(this.blueSquare, Phaser.Physics.ARCADE);
this.blueSquare.body.immovable = false;
this.blueSquare.body.collideWorldBounds = true;
this.blueSquare.body.setSize(34, 34, 0, 0);
this.blueSquare.angle = 0;
game.physics.arcade.velocityFromRotation(this.blueSquare.rotation, 0, this.blueSquare.body.velocity);
}
BlueSquare.prototype.update = function () {
var inputChanged = (
this.cursor.left != this.input.left ||
this.cursor.right != this.input.right ||
this.cursor.up != this.input.up ||
this.cursor.down != this.input.down
);
if (inputChanged)
{
if (this.blueSquare.id == myId)
{
this.input.x = this.blueSquare.x;
this.input.y = this.blueSquare.y;
this.input.angle = this.blueSquare.angle;
eurecaServer.handleKeys(this.input);
}
}
if (this.cursor.left)
{
this.blueSquare.body.velocity.x = -250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.right)
{
this.blueSquare.body.velocity.x = 250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.down)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 250;
}
else if (this.cursor.up)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = -250;
}
else
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 0;
}
}
BlueSquare.prototype.kill = function () {
this.alive = false;
this.blueSquare.kill();
}
GenerateCoin = function (game, goldCoin) {
this.game = game;
this.goldCoin = goldCoin;
x = 0;
y = 0;
this.coins = game.add.sprite(x, y, 'coin');
game.physics.enable(this.coins, Phaser.Physics.ARCADE);
this.coins.body.immovable = true;
this.coins.body.collideWorldBounds = true;
this.coins.body.setSize(16, 16, 0, 0);
}
window.onload = function() {
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (+new Date);
if ( msLeft < 1000 ) {
element.innerHTML = "Game Over!";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}countdown( "countdown", 5, 0 );
}
var game = new Phaser.Game(700, 600, Phaser.AUTO, 'Square Hunt', { preload: preload, create: eurecaClientSetup, update: update, render: render });
function preload () {
game.load.spritesheet('coin', 'assets/coin.png', 18, 18);
game.load.image('blueSquare', 'assets/blue-square.png');
game.load.image('redSquare', 'assets/red-square.png');
game.load.image('earth', 'assets/sand.png');
}
function create () {
game.world.setBounds(0, 0, 1500, 1500);
game.stage.disableVisibilityChange = true;
background = game.add.tileSprite(0, 0, 800, 600, 'earth');
background.fixedToCamera = true;
squareList = {};
player = new BlueSquare(myId, game, blueSquare);
squareList[myId] = player;
blueSquare = player.blueSquare;
blueSquare.x = Math.floor(Math.random() * 650);
blueSquare.y = Math.floor(Math.random() * 650);
blueSquare.bringToTop();
game.camera.follow(blueSquare);
game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
game.camera.focusOnXY(0, 0);
cursors = game.input.keyboard.createCursorKeys();
coinList = {};
goldCoin = new GenerateCoin(game, coins);
coinList = goldCoin;
coins = goldCoin.coins;
coins.x = Math.floor(Math.random() * 650);
coins.y = Math.floor(Math.random() * 650);
coins.bringToTop();
}
function update () {
if (!ready) return;
game.physics.arcade.collide(blueSquare, coins);
player.input.left = cursors.left.isDown;
player.input.right = cursors.right.isDown;
player.input.up = cursors.up.isDown;
player.input.down = cursors.down.isDown;
player.input.fire = game.input.activePointer.isDown;
player.input.tx = game.input.x+ game.camera.x;
player.input.ty = game.input.y+ game.camera.y;
background.tilePosition.x = -game.camera.x;
background.tilePosition.y = -game.camera.y;
for (var i in squareList)
{
if (!squareList[i]) continue;
var curBlue = squareList[i].blueSquare;
for (var j in squareList)
{
if (!squareList[j]) continue;
if (j!=i)
{
var targetBlue = squareList[j].blueSquare;
}
if (squareList[j].isBlue)
{
squareList[j].update();
}
}
}
}
function test(){
console.log('collsion');
}
function render () {}
Server.js Files
var express = require('express')
, app = express(app)
, server = require('http').createServer(app);
app.use(express.static(__dirname));
var clients = {};
var EurecaServer = require('eureca.io').EurecaServer;
var eurecaServer = new EurecaServer({allow:['setId', 'spawnBlueSquare', 'spawnCoins', 'kill', 'updateState']});
eurecaServer.attach(server);
eurecaServer.onConnect(function (conn) {
console.log('New Client id=%s ', conn.id, conn.remoteAddress);
var remote = eurecaServer.getClient(conn.id);
clients[conn.id] = {id:conn.id, remote:remote}
remote.setId(conn.id);
});
eurecaServer.onConnectionLost(function (conn) {
console.log('connection lost ... will try to reconnect');
});
eurecaServer.onDisconnect(function (conn) {
console.log('Client disconnected ', conn.id);
var removeId = clients[conn.id].id;
delete clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.kill(conn.id);
}
});
eurecaServer.exports.handshake = function()
{
for (var c in clients)
{
var remote = clients[c].remote;
for (var cc in clients)
{
var x = clients[cc].laststate ? clients[cc].laststate.x: 0;
var y = clients[cc].laststate ? clients[cc].laststate.y: 0;
remote.spawnBlueSquare(clients[cc].id, x, y);
}
}
}
eurecaServer.exports.handleKeys = function (keys) {
var conn = this.connection;
var updatedClient = clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.updateState(updatedClient.id, keys);
clients[c].laststate = keys;
}
}
server.listen(8000);
Instead of generating coins randomly positioned on each client, you could generate this random position(x and y) in server side(on conexion event) and then send this position to all clients so they can generate the coin in the same position.

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

Categories

Resources