Reset Valuable and repeated action - javascript

I am building a game, where the computer makes a patter of four colors and you have to remember the pattern and repeat it.
And it works almost fine, but there is one error which i cant figure out.
When i played a round and lost and the game restarts the level value goes to 2 instead of 1.
And when the new game starts the first two buttons get pressed at the same time.
At the first round everything works fine but the next round not.
var gamePattern = [];
var playerPattern = [];
var buttonColors = ["red", "blue", "green", "yellow"]
var level = 0;
$(".btn").click(function () {
if (patternDone) {
pressButton(this.id);
playerPattern.push(this.id);
checkAnswer();
}
});
function resetGame() {
gamePattern = [];
playerPattern = [];
gamePattern.length = 0;
playerPattern.length = 0;
patternDone = false;
level = 0;
$("h1").html("Press A Key to Start")
$(document).keypress(startGame);
}
//start
$(document).keypress(startGame);
//start Game
function startGame() {
level = level + 1;
console.log("level " + level);
console.log(level);
gamePattern = [];
playerPattern = [];
createLevel();
console.log(gamePattern)
playPattern();
patternDone = true;
$("h1").html("Level " + level)
}
//play the patter
async function playPattern() {
for (k = -1; k < level; k++) {
d = level - k;
// console.log(gamePattern);
abcColor = gamePattern[gamePattern.length - d];
console.log(abcColor);
await delay(1000);
pressButton(abcColor);
d = 0;
}
}
//create the level
function createLevel() {
for (y = 0; y <= level; y++) {
var randomColor = buttonColors[Math.floor(Math.random() * buttonColors.length)];
gamePattern.push(randomColor);
}
}
//update h1
function h1Level() {
levelCopy = level + 1;
$("h1").html("level " + levelCopy);
}
//pressButton
function pressButton(colord) {
// console.log(colord);
animatePress(colord);
playSound(nameSound = colord);
}
// Sound
function playSound(nameSound) {
var audio = new Audio("sounds/" + nameSound + ".mp3");
audio.play();
}
// animateClick
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
// console.log(currentColor);
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
//delay
const delay = millis => new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millis)
});
//Button click and deciding if its right
async function checkAnswer() {
if (playerPattern.length === gamePattern.length) {
if (playerPattern.join(',') === gamePattern.join(',')) {
$("h1").html("Correct!");
console.log("correct");
await delay(1000);
startGame();
} else if (playerPattern.join(',') !== gamePattern.join(',')) {
$("h1").html("Wrong!");
level = 0;
console.log("wrong");
await delay(3000);
resetGame();
}
}
}

Related

Repeat previous pattern (gamePatten array) one button at a time, before adding Next Sequence. Simon Game

I would like to setTimeout to every step/item from the GamePattern array. Suppose I am at LEVEL 4:
gamePattern [ 'red', 'blue', 'blue ] then Next Sequence.
But I need to run the sequence one-second gap between them, like 1sec to 'red', then 1sec to 'blue', 1sec to 'blue'...
Here is my entire code.
let userPattern = [];
const gameColors = ["green", "red", "yellow", "blue"];
let level = 0;
const sound = new Audio(`sounds/green.mp3`);
const wrong = new Audio("sounds/wrong.mp3");
//PLAYGAME
function playGame() {
document.querySelector("#overlay").style.display = "none";
level = 0;
gamePattern = [];
nextSequence();
}
//NEXT SEQUENCE
const nextSequence = function () {
document.querySelector(
"h2"
).innerHTML = `<h2 class="detach">LEVEL ${level}</span></h2>`;
userPattern = [];
let index = Math.round(Math.random() * 3);
let randomChosenColour = gameColors[index];
gamePattern.push(randomChosenColour);
animatePress(randomChosenColour);
};
function animatePress(buttoncolor) {
let button = document.querySelector(`#${buttoncolor}`);
button.classList.remove("hidden");
sound.play();
setTimeout(() => button.classList.add("hidden"), 200);
}
function userChoice(e) {
let colorClicked = e.target.classList[1];
animatePress(colorClicked);
userPattern.push(colorClicked);
checkAnswer(userPattern.length - 1);
}
for (let button of gameColors) {
document.querySelector(`.${button}`).addEventListener("click", userChoice);
}
//CHECK
function checkAnswer(currentlevel) {
if (userPattern[currentlevel] === gamePattern[currentlevel]) {
if (userPattern.length === gamePattern.length) {
previousPattern();
level++;
}
} else {
return gameOver();
}
}
//GAMEOVER
function gameOver() {
wrong.play();
//add eventlistener to restart the game
document.body.addEventListener("keypress", playGame);
//display an overlay GAME OVER SETUP.
document.querySelector("#overlay").style.display = "block";
document.querySelector("h2").innerHTML =
'<h2><span class="detach"> Lost at level: ' + level + "</span></h2>";
}
//START
document.body.addEventListener("keypress", playGame);
function previousPattern() {
//loop over the gamePatter in order to show the iteration 0.5 second gap.
for (let i = 1; i <= gamePattern.length; i++) {
setTimeout(() => {
animatePress(gamePattern[i - 1]);
}, 500 * i);
console.log(gamePattern.length, gamePattern);
if (i === gamePattern.length) {
return setTimeout(nextSequence, 1000 * i);
}
}
}
The thing is, The code doesn't show any improvement, and button animations overlap, and I don't know If I've messed up with so much setTimeout added.
Any hint? Thanks in advance

passing a simon game from jQuery to vanilla JS

Long story short, I made this Simon Game in a bootcamp a month ago in jQuery, but the days pass and I started to feel the necesity of translate it to pure vanilla javaScript.
the thing is that I feel stuck in the last part, when I have to check the answers of the game and add that to the gamePatern array and userChosenPattern.
here is the main part in jQuery
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function () {
if (!started) {
$("#level-title").text("level " + level);
nextSequence();
started = true;
}
});
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
$("#" + randomChosenColour)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100);
playSound(randomChosenColour);
}
$(".btn").click(function () {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
});
function checkTheAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("success");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
$("body").addClass("game-over");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
gameOverAudio();
$("#level-title").text("Game Over, Press Any Key to Restart");
$("#level-title").css("font-size", "2rem");
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
and here is the same part and the whole code but in vanilla JS
const buttonColors = ["red", "blue", "green", "yellow"];
const gamePattern = [];
const userClickedPattern = [];
const started = false;
const level = 0;
const body = document.querySelector("body");
const levelTitle = document.getElementById("level-title");
// to start the game
document.addEventListener("keypress", () => {
if (!started) {
levelTitle.innerHTML = `level ${level}`;
nextSequence();
sarted = true;
}
});
// generete the next sequence
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
let animationBtn = document.querySelector("#" + randomChosenColour);
animationBtn.classList.add("FadeInFadeOut");
setTimeout(() => {
animationBtn.classList.remove("FadeInFadeOut");
}, 50);
playSound(randomChosenColour);
}
// here we detect which button is pressed by the user
var bTn = document.getElementsByClassName("btn");
document.querySelectorAll(".btn").forEach((bt) => {
bt.onclick = () => {
let userChosenColor = bt.id;
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
};
});
// check the answer and dynamic of the game
const checkTheAnswer = (currentLevel) => {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("succes");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(() => {
nextSequence();
}, 1000);
}
} else {
body.classList.add("game-over");
setTimeout(() => {
body.classList.remove("game-over");
}, 200);
gameOverAudio();
levelTitle.innerHTML = `Game Over, Press Any Key to Restart`;
levelTitle.style.fontSize = "2rem";
startOver();
}
};
const startOver = () => {
level = 0;
gamePattern = [];
started = false;
};
// adudio stuff
const playSound = (name) => {
let audio = new Audio("sounds/" + name + ".mp3");
audio.play();
};
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
//animation in button
const animatePress = (currentColor) => {
const buttons = document.querySelector(`#${currentColor}`);
buttons.classList.add("pressed");
setTimeout(() => {
buttons.classList.remove("pressed");
}, 100);
};
console.log(gamePattern);
console.log(userClickedPattern);
Also here is the game in my codepen, it’s without the sounds for obvious reasons.
Simon Game

Chrome Extension - Running Sequential functions through promises not working

I have a chrome extension (JS) that I am building and when the user clicks on a button in the popup, the extension updates the chrome.storage.local to reflect what is on the popup and (in theory) when that is complete, it would run three content scripts. Unfortunately, the content script seem to start before the information is set in the popup.js.
I have tried Timeouts and Promises, however with both, it still runs the next function before the "chrome.storage.local.set" (in the updateStorage() function) is executed. Is there a better method/something that I am missing?
popup.js
console.log("popup.js");
function doContent() {
console.log("content1");
//checkboxes = document.getElementsByTagName("input");
//checkCheckboxes(checkboxes);
chrome.tabs.executeScript(null, { file: "content_addNote.js" });
}
function checkCheckboxes(checkboxes, orderArray) {
//console.log("checkboxes");
//console.log(checkboxes);
console.log("orderArray");
console.log(orderArray);
console.log("for loop running");
var ii = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") {
if (checkboxes[i].checked === false) {
console.log(i, orderArray[i], "will be removed for the list");
//console.log(orderArray[i]);
orderArray.splice(ii, 1);
ii = ii - 1;
console.log(orderArray);
}
ii += 1;
//console.log(i, checkboxes[i].checked);
}
}
console.log("for loop ended");
console.log("Output from checkCheckboxes");
console.log(orderArray);
return orderArray;
}
function updateStorage() {
console.log("updateStorage");
var emailSelect = document.getElementById("SelEmailType");
var emailType = emailSelect.options[emailSelect.selectedIndex].id;
if (document.getElementById("itemInfo").innerHTML === "Placeholder") {
console.log("Error. Placeholder not found");
} else {
var storedLegal = chrome.storage.local.get("newStorage", function (items) {
var newArray = { ...items };
console.log(newArray);
var orderList = items.newStorage.src_items;
console.log("orderList", orderList);
//console.log("indexOf", orderList.indexOf("\n"));
var orderArray = orderList.split("\n");
var checkboxes = new Array();
checkboxes = document.getElementsByTagName("input");
updatedOrder = checkCheckboxes(checkboxes, orderArray);
console.log(updatedOrder);
arraString = updatedOrder.join("\n");
//console.log(arraString);
//alert(arraString);
newArray.newStorage.src_items = arraString;
newArray.newStorage.src_emailType = emailType;
console.log("start newArray");
console.log(newArray);
console.log("end newArray");
console.log(newArray.newStorage);
chrome.storage.local.clear();
chrome.storage.local.set({
newStorage: newArray.newStorage,
});
//chrome.runtime.sendMessage({ newStorage: newArray.newStorage });
console.log("stored");
//console.log(chrome.runtime.local.get({ newStorage }));
});
}
console.log("End storedLegal");
return;
}
function one_by_one(objects_array, iterator, callback) {
/* var x = 1;
var y = null; // To keep under proper scope
setTimeout(function () {
x = x * 3 + 2;
y = x / 2;
}, 500); */
var start_promise = objects_array.reduce(function (prom, object) {
return prom.then(function () {
//var y = null; // To keep under proper scope
/* setTimeout(function () {
x = x * 3 + 2;
y = x / 2;
}, 500);
x = 1;
y = null; */
return chrome.tabs.executeScript(null, { file: object }); //iterator(object);
});
}, Promise.resolve()); // initial
if (callback) {
start_promise.then(callback);
} else {
return start_promise;
}
}
/*
function processArray(arr, fn) {
return arr.reduce(
(p, v) => p.then((a) => fn(v).then((r) => a.concat([r]))),
Promise.resolve([])
);
} */
function doContent2() {
console.log("doContent2");
updateStorage();
fileFunctions = [
"content2.js",
"content_addShippingNote.js",
"content_addNote.js",
"disconnect.js",
];
var x = 1;
var y = null; // To keep under proper scope
console.log("fileFunctions ");
new Promise((resolve, reject) => {
// Promise #1
updateStorage();
console.log("Promise #1 ");
setTimeout(function () {
x = x * 3 + 2;
y = x / 2;
}, 1000);
resolve();
})
.then((result) => {
var storedLegal = chrome.storage.local.get("newStorage", function (
items
) {
if ((items = undefined)) {
console.log("item not found");
// To keep under proper scope
setTimeout(function () {
x = 1;
y = null;
x = x * 3 + 2;
y = x / 2;
}, 500);
}
//console.log(items);
});
// Promise #2
chrome.tabs.executeScript(null, { file: "content2.js" });
console.log("Promise #2 ");
return result;
})
.then((result) => {
// Promise #3
chrome.tabs.executeScript(null, { file: "content_addShippingNote.js" });
console.log("Promise #3 ");
return result;
})
.then((result) => {
// Promise #3
chrome.tabs.executeScript(null, { file: "content_addNote.js" });
console.log("Promise #4 ");
return result;
});
//processArray(fileFunctions, runScript).then(console.log);
//fileFunctions.forEach(runScript);
//one_by_one(fileFunctions, "", "");
/* var promised = new Promise(updateStorage).then((result, err) => {
console.log("YA");
fileFunctions.forEach(runScript);
}); */
document.getElementById("btnCreateEmail").addEventListener("click", null);
//fileFunctions.forEach(runScript);
/* chrome.tabs.executeScript(null, { file: "content2.js" }),
chrome.tabs.executeScript(null, { file: "content_addShippingNote.js" }),
chrome.tabs.executeScript(null, { file: "content_addNote.js" }),
chrome.tabs.executeScript(null, { file: "disconnect.js" }), */
}
function runScript(fileName, index) {
console.log(index, ": ", fileName);
chrome.tabs.executeScript(null, { file: fileName });
}
function clearStorage() {
chrome.tabs.executeScript(null, { file: "disconnect.js" });
alert("local cleared");
}
function orderToHTML(orderList) {
var orderArray = orderList.split("\n");
// Draw HTML table
var perrow = 2, // cells per row
html = "<table><tbody>";
// Loop through array and add table cells
for (var i = 0; i < orderArray.length; i++) {
html +=
"<tr><td><input type=" &
"checkbox" &
" " &
"id=" &
i &
"/></td><td>" &
orderArray[i] &
"</td></tr>";
var next = i + 1;
if (next % perrow == 0 && next != orderArray.length) {
html += "</tr><tr>";
}
}
html += "</tbody></table>";
// Attach HTML to container
return html;
}
function setWaitPeriod(time) {
var x = 1;
var y = null; // To keep under proper scope
setTimeout(function () {
x = x * 3 + 2;
y = x / 2;
}, time);
}
//window.onload = function () {
//console.log("window.onload");
chrome.runtime.sendMessage({ popupOpen: true });
var port = chrome.runtime.connect();
chrome.runtime.onMessage.addListener((msg, sender) => {
// First, validate the message's structure.
if (msg.from === "content" && msg.subject === "showPageAction") {
document.getElementById("container").innerHTML = msg.container;
document.getElementById("itemInfo").innerHTML = msg.itemInfo;
}
});
document.getElementById("btnCreateEmail").addEventListener("click", doContent2);
//document.getElementById("btnClear").addEventListener("click", clearStorage);
//});

Run function only once until onmouseout

I have an anchor tag that plays a sound everytime the link is hovered:
<a onmouseenter="playAudio();">LINK</a>
However, when hovered, the link creates some characters that, if I keep moving the mouse inside the element, it keeps playing the sound over and over again.
Is there a way to play the onmouseenter function only once until it has detected the event onmouseout?
I've tried adding:
<a onmouseenter="playAudio();this.onmouseenter = null;">LINK</a>
but then it only plays the sound once.
Here goes the TextScramble animation function:
// ——————————————————————————————————————————————————
// TextScramble
// ——————————————————————————————————————————————————
class TextScramble {
constructor(el) {
this.el = el
this.chars = '!<>-_\\/[]{}—=+*^?#________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({
from,
to,
start,
end
})
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let {
from,
to,
start,
end,
char
} = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
// ——————————————————————————————————————————————————
// Configuration
// ——————————————————————————————————————————————————
const phrases = [
'MAIN_HUB'
]
const el = document.querySelector('.link_mainhub')
const fx = new TextScramble(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {});
}
el.addEventListener('mouseenter', next);
<a class="link_mainhub" onmouseenter="playAudio();">LINK</a>
Thanks.
Set a variable when you start playing the audio, and check for this before playing it again. Have the animation unset the variable when it's done.
function audioPlaying = false;
function playAudio() {
if (!audioPlaying) {
audioPlaying = true;
audioEl.play();
}
}
const next = () => {
fx.setText(phrases[counter]).then(() => {
audioPlaying = false;
});
}

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.

Categories

Resources