everyone! My name is Kate and I am a beginner in developing. Currently I am working on my test project, called "Simon game". I finished it but it doesn't work in a proper way. I checked the code million times, but can't find any errors. Please, look through it and if you can, please, help me to correct it.
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;
}
});
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
userCLickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkAnswer(userClickedPattern.length-1);
});
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
if (userClickedPattern.length === gamePattern.length) {
setTimeOut(function () {
nextSequence();
}, 1000);
}
} else {
playSound("wrong");
$("body").addClass("game-over");
$("#level-title").text("Game over, Press Any Key To Restart");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
I don't understand why the website doesn't react to a click on a button.
I check the button section, everything seems fine 🤷♀️
I have this problem: I have two buttons btStop and btRace . BtPlays clicks all the buttons bt1 and all my cars are driving at the same time. BtStop works exactly the same but it stops the animation. My problem is, that when I once click btRace and animation is done I cannot click it again unless I click btStop, which is misleading because animation is already stopped.
Is there a way to make btPlay active again after the animation is finished?
I have long code so I am pasting showButtons method
showButtons(bt1, bt2, img, editingCarId) {
let playBts = document.querySelectorAll('.play')
function animation(img) {
let status = 'started';
let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
aPICallCarEngineState.processRequestJSON((res) => {
// let resStr = JSON.stringify(res);
// console.log('I got ' + res)
res.velocity = res.velocity * 0.01
// res.distance = res.distance * 0.001
res.distance = 500;
// ===========Animation===================
img.style.animation = `car_move ${res.velocity}s ease-in`
})
}
//================Stop Animation===============
function stopAnimation() {
img.style.animation = 'none'
console.log(bt2 + 'stopp')
}
bt1.addEventListener('click', () => {
animation(img)
});
bt2.addEventListener('click', () => {
stopAnimation()
})
//=================Button start all animations ====================
this.btRace.addEventListener('click', () => {
bt1.click();
})
//=================Button stop all animations ====================
this.btStop.addEventListener('click', () => {
bt2.click();
})
}
invoke:
constructor:
this.table.appendTableHeadButton('RACE!')
this.table.appendTableHeadButtonStop('stop')
Buttoncreator:
appendTableHeadButtonStop(text) {
let td = document.createElement('td');
this.btStop = document.createElement('button');
this.btStop.innerText = text;
this.btStop.style.backgroundColor = 'red';
td.appendChild(this.btStop);
let bt = this.btStop;
this.headeRow.appendChild(td);
}
showButtons(bt1, bt2, img, editingCarId) {
let playBts = document.querySelectorAll('.play')
let isAnimating = false;
function animation(img) {
isAnimating = true;
btRace.disabled = true;
let status = 'started';
let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
aPICallCarEngineState.processRequestJSON((res) => {
// let resStr = JSON.stringify(res);
// console.log('I got ' + res)
res.velocity = res.velocity * 0.01
// res.distance = res.distance * 0.001
res.distance = 500;
// ===========Animation===================
img.style.animation = `car_move ${res.velocity}s ease-in`
img.addEventListener('animationend', () => {
isAnimating = false;
btRace.disabled = false;
});
});
}
//================Stop Animation===============
function stopAnimation() {
isAnimating = false;
btRace.disabled = false;
img.style.animation = 'none'
console.log(bt2 + 'stopp')
}
bt1.addEventListener('click', () => {
animation(img)
});
bt2.addEventListener('click', () => {
stopAnimation()
});
//=================Button start all animations ====================
this.btRace.addEventListener('click', () => {
bt1.click();
});
//=================Button stop all animations ====================
this.btStop.addEventListener('click', () => {
bt2.click();
});
}
I am adding a flag to check the state of animation, and then toggle disabled property of btRace button respectively.
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();
}
}
}
I wanted to make a FPS Unlimiter Userscript for gpop.io because the current fps cap is 60 and wanted to increase to 240fps and I don't understand JavaScript well enough to know what I am doing and am requesting help, The Section Of pageScript.js, I have The pageScript.js in the URL and The Code Below
!function pageScript() {
let speedConfig = {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
};
const emptyFunction = () => {};
const originalClearInterval = window.clearInterval;
const originalclearTimeout = window.clearTimeout;
const originalSetInterval = window.setInterval;
const originalSetTimeout = window.setTimeout;
const originalPerformanceNow = window.performance.now.bind(
window.performance
);
const originalDateNow = Date.now;
const originalRequestAnimationFrame = window.requestAnimationFrame;
let timers = [];
const reloadTimers = () => {
console.log(timers);
const newtimers = [];
timers.forEach((timer) => {
originalClearInterval(timer.id);
if (timer.customTimerId) {
originalClearInterval(timer.customTimerId);
}
if (!timer.finished) {
const newTimerId = originalSetInterval(
timer.handler,
speedConfig.cbSetIntervalChecked
? timer.timeout / speedConfig.speed
: timer.timeout,
...timer.args
);
timer.customTimerId = newTimerId;
newtimers.push(timer);
}
});
timers = newtimers;
};
window.addEventListener("message", (e) => {
if (e.data.command === "setSpeedConfig") {
speedConfig = e.data.config;
reloadTimers();
}
});
window.postMessage({ command: "getSpeedConfig" });
window.clearInterval = (id) => {
originalClearInterval(id);
timers.forEach((timer) => {
if (timer.id == id) {
timer.finished = true;
if (timer.customTimerId) {
originalClearInterval(timer.customTimerId);
}
}
});
};
window.clearTimeout = (id) => {
originalclearTimeout(id);
timers.forEach((timer) => {
if (timer.id == id) {
timer.finished = true;
if (timer.customTimerId) {
originalclearTimeout(timer.customTimerId);
}
}
});
};
window.setInterval = (handler, timeout, ...args) => {
console.log("timeout ", timeout);
if (!timeout) timeout = 0;
const id = originalSetInterval(
handler,
speedConfig.cbSetIntervalChecked ? timeout / speedConfig.speed : timeout,
...args
);
timers.push({
id: id,
handler: handler,
timeout: timeout,
args: args,
finished: false,
customTimerId: null,
});
return id;
};
window.setTimeout = (handler, timeout, ...args) => {
if (!timeout) timeout = 0;
return originalSetTimeout(
handler,
speedConfig.cbSetTimeoutChecked ? timeout / speedConfig.speed : timeout,
...args
);
};
// performance.now
(function () {
let performanceNowValue = null;
let previusPerformanceNowValue = null;
window.performance.now = () => {
const originalValue = originalPerformanceNow();
if (performanceNowValue) {
performanceNowValue +=
(originalValue - previusPerformanceNowValue) *
(speedConfig.cbPerformanceNowChecked ? speedConfig.speed : 1);
} else {
performanceNowValue = originalValue;
}
previusPerformanceNowValue = originalValue;
return Math.floor(performanceNowValue);
};
})();
// Date.now
(function () {
let dateNowValue = null;
let previusDateNowValue = null;
Date.now = () => {
const originalValue = originalDateNow();
if (dateNowValue) {
dateNowValue +=
(originalValue - previusDateNowValue) *
(speedConfig.cbDateNowChecked ? speedConfig.speed : 1);
} else {
dateNowValue = originalValue;
}
previusDateNowValue = originalValue;
return Math.floor(dateNowValue);
};
})();
// requestAnimationFrame
(function () {
let dateNowValue = null;
let previusDateNowValue = null;
const callbackFunctions = [];
const callbackTick = [];
const newRequestAnimationFrame = (callback) => {
return originalRequestAnimationFrame((timestamp) => {
const originalValue = originalDateNow();
if (dateNowValue) {
dateNowValue +=
(originalValue - previusDateNowValue) *
(speedConfig.cbRequestAnimationFrameChecked
? speedConfig.speed
: 1);
} else {
dateNowValue = originalValue;
}
previusDateNowValue = originalValue;
const dateNowValue_MathFloor = Math.floor(dateNowValue);
const index = callbackFunctions.indexOf(callback);
let tickFrame = null;
if (index == -1) {
callbackFunctions.push(callback);
callbackTick.push(0);
callback(dateNowValue_MathFloor);
} else if (speedConfig.cbRequestAnimationFrameChecked) {
tickFrame = callbackTick[index];
tickFrame += speedConfig.speed;
if (tickFrame >= 1) {
while (tickFrame >= 1) {
callback(dateNowValue_MathFloor);
window.requestAnimationFrame = emptyFunction;
tickFrame -= 1;
}
window.requestAnimationFrame = newRequestAnimationFrame;
} else {
window.requestAnimationFrame(callback);
}
callbackTick[index] = tickFrame;
} else {
callback(dateNowValue_MathFloor);
}
});
};
window.requestAnimationFrame = newRequestAnimationFrame;
})();
}()
//# sourceURL=pageScript.js
I was trying to read through the code to find what was capping the fps but I wasn't able to find anything that was easy enough for me to understand.
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.