How to turning Javascript snake correctly? - javascript

Snake is moving and turning correctly, when it has only one part, after add another part it doesn't like a snake;
I think my problem is in forEach method of full_snake div.
How to write the coordinates of each child in full_snake during the turn so that only the first child moves and the rest follow in its footsteps.
Directions work with this code, but all children have the same coordinates in the turn functions.
How to solve this?
This's my code:
class Snake {
snake_box = document.getElementById('snakeBox');
full_snake = document.getElementById('snake');
snakeLength = [];
snake;
x = 0;
y = 0
snakeMoveLeft;
snakeLeft = false;
snakeMoveRight;
snakeRight = true;
snakeMoveUp;
snakeUp = false;
snakeMoveDown;
snakeDown = false;
constructor() {
this.snakeLength.push('',);
this._createSnake();
this._moveSnake();
}
_createSnake() {
for (let i = 0; i < this.snakeLength.length; i++) {
this.snake = document.createElement('div');
this.snake.style.width = '1rem';
this.snake.style.height = '1rem';
this.snake.style.position = 'absolute';
this.snake.style.backgroundColor = 'green';
this.snake.style.marginLeft = '.1rem';
}
this.full_snake.appendChild(this.snake);
}
_moveSnake() {
this.full_snake.style.left = this.x + 'px';
this.full_snake.style.top = this.y + 'px';
this.snakeMoveLeft = setInterval(() => {
this.x += 20;
this.full_snake.style.left = this.x + 'px';
}, 500);
}
_turnLeft() {
this.snakeLeft = true;
this.snakeRight = false;
this.snakeUp = false;
this.snakeDown = false;
clearInterval(this.snakeMoveUp);
clearInterval(this.snakeMoveDown)
this.snakeMoveLeft = setInterval(() => {
this.full_snake.childNodes.forEach(e => {
this.x -= 20;
e.style.left = this.x + 'px';
})
}, 500);
}
_turnRight() {
this.snakeRight = true;
this.snakeLeft = false;
this.snakeUp = false;
this.snakeDown = false;
clearInterval(this.snakeMoveDown)
clearInterval(this.snakeMoveUp);
this.snakeMoveRight = setInterval(() => {
this.full_snake.childNodes.forEach(e => {
this.x += 20;
e.style.left = this.x + 'px';
})
}, 500);
}
_turnUp() {
this.snakeUp = true;
this.snakeLeft = false;
this.snakeRight = false;
this.snakeDown = false;
clearInterval(this.snakeMoveRight);
clearInterval(this.snakeMoveLeft);
this.snakeMoveUp = setInterval(() => {
this.full_snake.childNodes.forEach(e => {
this.y -= 20;
e.style.top = this.y + 'px';
})
}, 500);
}
_turnDown() {
this._createSnake();
this.snakeDown = true;
this.snakeUp = false;
this.snakeLeft = false;
this.snakeRight = false;
clearInterval(this.snakeMoveLeft);
clearInterval(this.snakeMoveRight)
this.snakeMoveDown = setInterval(() => {
this.y += 20;
this.full_snake.style.top = this.y + 'px';
}, 500)
}
_move() {
document.addEventListener('keydown', e => {
if (e.key === 'ArrowUp') {
if (this.snakeLeft === true || this.snakeRight === true) {
this._turnUp();
}
}
});
document.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') {
if (this.snakeLeft === true || this.snakeRight === true) {
this._turnDown();
}
}
})
document.addEventListener('keydown', e => {
if (e.key === 'ArrowLeft') {
if (this.snakeLeft === false && this.snakeRight === false) {
this._turnLeft();
}
}
});
document.addEventListener('keydown', e => {
if (e.key === 'ArrowRight') {
if (this.snakeLeft === false && this.snakeRight === false) {
this._turnRight();
}
}
})
}
}
new Snake()._move();

Related

I do not know how to limit the time in between calling my function

//let screenWidth = window.screen.width;
//let screenHeight = window.screen.height;
let screenWidth = 800;
let screenHeight = 600;
let assets = {};
let frames = 60;
let score = 0;
let lives = 3;
let player;
// let enemie;
//let enemies;
let bullet;
//let bullets;
let powerup = 0;
let gameOver = true;
function drawScoreBoard() {
textSize(20);
fill('white');
text(`Score: ${score} / Lives: ${lives}`, 20, 40);
}
function preload() {
assets.player = loadImage('assets/Player.png');
assets.enemie = loadImage('assets/Enemie.png');
assets.bulletRight = loadImage('assets/Bullet_Right.png');
assets.bulletLeft = loadImage('assets/Bullet_Left.png');
assets.bulletUp = loadImage('assets/Bullet_Up.png');
assets.bulletDown = loadImage('assets/Bullet_Down.png');
}
function setup() {
bullets = createGroup();
enemies = createGroup();
assets.player.resize(30, 30);
assets.enemie.resize(30, 30);
assets.bulletRight.resize(30, 30);
assets.bulletLeft.resize(30, 30);
assets.bulletUp.resize(30, 30);
assets.bulletDown.resize(30, 30);
createCanvas(screenWidth, screenHeight);
}
function createBullet(){
let numList = [0, 90, 180, 270, 360];
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let randomdirection = numList[Math.floor(Math.random() * numList.length)];
let bullet = createSprite(bulletDirection[(Math.round(player.getDirection()/90))]);
enemie.centerX = random(0, screenWidth);
enemie.setSpeed(random(1,10));
enemie.setDirection(randomdirection);
enemie.setCollider("circle");
bullets.add(bullet);
}
function createPlayer(){
player = createSprite(assets.player);
player.bottom = screenHeight - 20;
player.centerX = screenWidth / 2;
}
function shoot(amountofbulletstobeshot) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
// bullet.direction = player.direction;
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
// console.log('The players current direction right now is: ' + player.getDirection());
}
function shooting() {
if (keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
}
else {
shoot(1);
}
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
function updateplayer() {
//movement
if (keyIsDown) {
if (keyIsDown(KEY.RIGHT_ARROW)) {
player.setVelocity(6, 0);
}
if (keyIsDown(KEY.LEFT_ARROW)) {
player.setVelocity(6, 180);
}
if (keyIsDown(KEY.UP_ARROW)) {
player.setVelocity(6, 270);
}
if (keyIsDown(KEY.DOWN_ARROW)) {
player.setVelocity(6, 90);
}
}
//dont go offscreen
if (player.left < 0) {
player.left = 0;
}
if (player.right > screenWidth) {
player.right = screenWidth;
}
if (player.top < 0) {
player.top = 0;
}
if (player.bottom > screenHeight) {
player.bottom = screenHeight;
}
enemies.overlap(player, HandlePlayerEnemieCollision);
//end up updateplayer
}
function updateEnemie() {
if (frameCount % 1 === 0) {
let directions = ["LEFT", "RIGHT", "UP", "DOWN"];
let direction = random(directions);
if (direction === "LEFT" && enemie.left > 0) {
enemie.centerX -= 5;
}
if (direction === "RIGHT" && enemie.right < screenWidth) {
enemie.centerX += 5;
}
if (direction === "UP" && enemie.top > 0) {
enemie.centerY -= 5;
}
if (direction === "DOWN" && enemie.bottom < screenHeight) {
enemie.centerY += 5;
}
}
}
function createEnemie() {
let directions = [270, 180, 0, 90];
direction = directions[(Math.floor(Math.random() * 5))];
enemies.overlap(bullets, HandleEnemieBulletCollision);
if (frameCount % 60 === 0) {
enemie = createSprite(assets.enemie);
enemie.centerX = Math.floor(Math.random() * 300) + 100;
enemie.centerY = Math.floor(Math.random() * 300) + 100;
enemie.setVelocity(Math.floor(Math.random() * 5) + 1, direction);
enemies.add(enemie);
}
}
function HandleEnemieEdgeCollision(enemie, edge) {
if (enemie.centerY === screenWidth) {
enemie.remove();
}
}
function HandleEnemieBulletCollision(enemie, bullet) {
enemie.remove();
bullet.remove();
score++;
}
function HandlePlayerEnemieCollision(player, enemie) {
enemie.remove();
player.remove();
lives--;
if (lives === 0) {
gameOver = true;
}
createPlayer();
}
/*
function updateEnemie() {
player.setVelocity(7, player.direction);
}
*/
function cheat() {
score = (score + 1000000);
lives = (lives + 1000000);
cheats = 'on';
if (cheats === 'on') {
textSize(50);
fill('yellow');
text('CHEATS ACTIVATED', 400, 300);
}
}
/*
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
*/
function drawGameOverScreen() {
background("black");
textAlign(CENTER);
fill("white");
textSize(40);
text("WELCOME", screenWidth/2, screenHeight/2);
textSize(20);
text("Press SPACE to play!", screenWidth/2, screenHeight/2 + 100);
if (keyWentDown(KEY.SPACE)){
resetGame();
gameOver = false;
}
}
function resetGame(){
score = 0;
lives = 3;
createPlayer();
}
function drawGame() {
background('lightgreen');
drawScoreBoard();
updateplayer();
drawSprites();
shooting();
// updateEnemie();
createEnemie();
}
function draw() {
if (gameOver === true) {
drawGameOverScreen();
} else {
drawGame();
}
}
There is my code, I want to add a time limit for how many seconds it takes until you can shoot again, right now you can just spam and make all of the bullets go in a straight line I need to wait before I let the player shoot again, Thanks! This will help out allot and i neede this in as few minutes as possible.
Use a flag to know when shooting is enabled and disabled. After each shot disable the ability to shoot. Then use a setTimeout to enable the shooting after a certain amount of time.
let shootingEnabled = true;
function tempDisableShooting(duration) {
shootingEnabled = false;
setTimeout(() => {
shootingEnabled = true;
}, duration);
}
function shooting() {
if (shootingEnabled && keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
} else {
shoot(1);
}
tempDisableShooting(1000); // Disable shooting for 1 second.
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
Add property to track the disabled state of the shooting and a constant for the delay time in milliseconds.
let shootDisabled = false;
const shootDelayMS = 300;
Update your shoot function to only shoot if shootDisabled == false, update the shootDisabled to true after each shot, and to triggers a setTimeout which waits shootDelayMS milliseconds before setting shootDisabled to false again.
function shoot(amountofbulletstobeshot) {
if (shootDisabled == false) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
shootDisabled = true;
setTimeout(() => shootDisabled = false, shootDelayMS );
}
}
one way is the hold the data in two variables: is_shooting, shot_reset.
if(is_shooting){
if(shot_reset>=x){ //x is frame count till able to shoot again)
shot_reset==0;
is_shooting=false;
}else{
shot_reset++
}
}

player.js:1 Uncaught SyntaxError: Identifier 'Player' has already been declared laravel-6

i have an laravel project and just implemented some scripts in it
and i keep gettinf this error
Uncaught SyntaxError: Identifier 'Player' has already been declared
at player.js:1
Uncaught SyntaxError: Identifier 'canvas' has already been declared
at tetris.js:1
i only get this error while working with laravel because the code works in a normal html file.
this is my javascript:
player.js
class Player
{
constructor()
{
this.pos = {x:0,y:0};
this.matrix = null;
this.score = 0;
}
}
tetris.jsconst canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#cbc7ca';
context.strokeRect(0,0, canvas.width, canvas.height);
function arenaSweep() {
let rowCount = 1
outer: for(let y = arena.length - 1; y > 0; --y) {
for(let x = 0; x < arena[y].length; ++x) {
if(arena[y][x] === 0){
continue outer;
}
}
const row = arena.splice(y, 1)[0].fill(0);
arena.unshift(row);
++y;
player.score += rowCount * 10;
rowCount *= 2;
}
}
function collide(arena, player){
const [m, o] = [player.matrix, player.pos];
for(let y = 0; y < m.length; ++y) {
for(let x = 0; x < m[y].length; ++x){
if(m[y][x] !== 0 &&
(arena[y + o.y] &&
arena[y + o.y][x + o.x]) !== 0)
return true;
}
}
return false;
}
function createMatrix(w, h){
const matrix = [];
while( h--) {
matrix.push(new Array(w).fill(0));
}
return matrix
}
function draw() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(arena, {x:0, y:0});
drawMatrix(player.matrix, player.pos );
}
function createPiece(type) {
if( type === 'T'){
return [
[0,0,0],
[1,1,1],
[0,1,0],
];
}
else if(type === 'O'){
return [
[2,2],
[2,2]
];
}
else if( type === 'L'){
return [
[0,3,0],
[0,3,0],
[0,3,3],
];
}
else if( type === 'J'){
return [
[0,4,0],
[0,4,0],
[4,4,0],
];
}
else if( type === 'I'){
return [
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
];
}
else if( type === 'Z'){
return [
[6,6,0],
[0,6,6],
[0,0,0],
];
}
else if( type === 'S'){
return [
[0,7,7],
[7,7,0],
[0,0,0],
];
}
}
function drawMatrix(matrix, offset){
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
context.fillStyle = colors[value];
context.fillRect(x + offset.x,
y + offset.y,
1,1);
}
});
});
}
function merge(arena, player) {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
function playerDrop() {
player.pos.y++;
if(collide(arena, player)) {
player.pos.y--;
merge(arena,player);
playerReset();
arenaSweep();
updateScore();
}
dropCounter = 0;
}
function playerMove(dir) {
player.pos.x += dir;
if(collide(arena, player)) {
player.pos.x -= dir;
}
}
function playerReset() {
const pieces = 'ILJOSZ';
player.matrix = createPiece(pieces[pieces.length * Math.random() | 0]);
player.pos.y = 0;
player.pos.x = (arena[0].length / 2 | 0) -
(player.matrix[0].length / 2 | 0);
if(collide(arena,player)) {
arena.forEach(row => row.fill(0));
player.score = 0;
playerReset();
}
}
function playerRotate(dir){
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
while (collide(arena, player)) {
player.pos.x += offset;
offset = -(offset +(offset > 0 ? 1 : -1 ));
if(offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
function rotate(matrix, dir){
for(let y = 0; y < matrix.length;++y) {
for(let x = 0; x < y; ++x) {
[
matrix[x][y],
matrix[y][x],
] = [
matrix[y][x],
matrix[x][y],
];
}
}
if(dir > 0){
matrix.forEach(row => row.reverse());
}else{
matrix.reverse();
}
}
let dropCounter = 0;
let dropInterval = 1000;
let lasttime = 0;
function update(time = 0) {
const deltaTime = time - lasttime;
lasttime = time;
dropCounter += deltaTime;
if(dropCounter > dropInterval){
playerDrop();
}
draw();
requestAnimationFrame(update);
}
function updateScore() {
document.getElementById('score').innerText = player.score;
}
const colors =[
null,
'purple',
'yellow',
'orange',
'blue',
'cyan',
'red',
'green',
];
const arena = createMatrix(12, 20);
const player = new Player;
document.addEventListener('keydown', event => {
if (event.keyCode === 37){
playerMove(-1);
}
else if(event.keyCode === 39){
playerMove(1);
}
else if(event.keyCode === 40){
playerDrop();
}
else if(event.keyCode === 90) {
playerRotate(-1);
}
else if(event.keyCode === 88) {
playerRotate(1);
}
})
playerReset();
updateScore();
update();
this is my blade template:
#section('content')
<div id="score">0</div>
<canvas id="tetris" width="240" height="400"></canvas>
<script type="application/javascript" src="{{asset('js/player.js')}}"></script>
<script type="application/javascript" src="{{asset('js/tetris.js')}}"></script>
#endsection`

Won't let me set class name of a Javascript created div

I'm using a function to create a div element on the page. I want to assign a className but I get the error: cannot set property className of undefined.
But I did this in another function and it worked. Why is this one not working?
If I failed to provide the code relevant to the problem I apologize. I'm in a rush and included code that I thought might be relevant in order of relevancy.
** WORKING FUNCTION **
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb'; //DOESN'T THROW ERROR ----
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
** NOT WORKING FUNCTION **
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet'; //THROWS ERROR -----
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x +
(player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y +
(player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
** STARTING CODE THAT MIGHT HAVE CONTEXT IDK**
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
** OTHER CODE THAT MIGHT HAVE CONTEXT **
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * .
gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
** JUST IN CASE YOU NEED -- idk its hard for me to keep track of everything that might be related to the problem... sorry.. **
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
** FULL JS FILE: BE WARNED IM VERY NEW AND THIS IS NOT GOOD CODE **
const title = document.querySelector(".title");
const gameMessage = document.querySelector(".gameMessage");
function changeColor() {
let newArray = ["darksalmon", "lightsalmon", "crimson", "red", "deeppink", "yellowgreen", "ghostwhite"];
let random = Math.floor(Math.random() * Math.floor(newArray.length - 1));
if (title.style.color != newArray[random]) {
title.style.color = newArray[random];
console.log(title.style.color);
} else {
changeColor();
}
}
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
function playGame() {
if (player.inplay) {
moveBomb();
if(player.x < (gameArea.offsetWidth / 2)) {
console.log('WORKED');
makeBullet();
}
if (player.swing){
player.plane.style.backgroundImage ='url(guts1.png)';
player.swing = false;
//player.plane.style.width = 210 + 'px';
}
if (keys['x'] && player.enemy && isCollide(player.plane, player.enemy)) {
removeEnemy();
}
if (player.enemy) {
if (isCollide(player.plane, player.enemy)) {
player.getHit++;
if (player.getHit > player.getHitMax){
endGame();
}
} else {
player.getHit = 0;
}
if (player.x > player.enemy.x) {
player.enemy.x += 1;
}
if (player.x < player.enemy.x) {
player.enemy.x -= 1;
}
player.enemy.style.left = player.enemy.x + 'px';
}
if (player.hasBomb >= player.maxBombs && player.bomb.y > gameArea.offsetHeight - 20) {
endGame();
}
if (keys.space) {
makeBomb()
}
if (keys.ArrowUp && player.y > 0) {
player.y -= (player.speed + (player.speed * .5));
}
if (keys.ArrowDown && player.y < (gameArea.offsetHeight - player.plane.offsetHeight - 30)) {
player.y += (player.speed + (player.speed * .5));
}
if (keys.ArrowLeft && player.x > 0) {
player.x -= (player.speed + (player.speed * .5));
}
if (keys.ArrowRight && player.x < (gameArea.offsetWidth)) {
player.x += (player.speed - (player.speed * .5));
}
if (player.x == (gameArea.offsetWidth)) {
player.x = 0;
player.score -= 100;
if (!player.enemy) {
makeEnemy();
}
}
player.score -= .4;
if (player.score < 0) {
player.score = 0;
}
player.x += (player.speed * .5);
score.innerHTML = Math.floor(player.score) + ' Bombs left: ' + (player.maxBombs - player.hasBomb);
player.plane.style.left = player.x + 'px';
player.plane.style.top = player.y + 'px';
window.requestAnimationFrame(playGame);
}
}
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false){
playerPlane = player.plane;
player.plane.style.backgroundImage ='url(guts2.png)';
setTimeout(function () {
player.swing = true;
}, 300);
//player.plane.style.width = 400 + 'px';
}
console.log(tempKey)
console.log(keys);
}
function pressOff(e) {
e.preventDefault();
let tempKey = (e.key== " ") ? "space" : e.key;
console.log(tempKey);
// if (keys['x'] && player.swing){
// playerPlane = player.plane;
// player.plane.style.backgroundImage ='url(guts1.png)';
// player.swing = false;
// //player.plane.style.width = 210 + 'px';
//
// }
if (keys['space'] || keys['x']) {
keys['space'] = 0;
keys['x'] = 0;
}
keys[tempKey] = false;
console.log(keys);
}
function moveBomb() {
let bombs = document.querySelectorAll('.bomb');
bombs.forEach(function (item) {
item.y += 10;
item.style.top = item.y + 'px';
if (item.y > gameArea.offsetHeight) {
item.parentNode.removeChild(item);
player.bomb = null;
}
if (player.enemy && player.bomb) {
if (isCollide(item, player.enemy)) {
player.hit++;
}
}
if (player.hit > player.hitMax) {
item.parentNode.removeChild(item);
player.bomb = null;
player.score += 2000;
player.hit = 0;
player.hasBomb -= 2
gameArea.removeChild(player.enemy);
player.enemy = null;
}
})
}
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
//function getLocationX(a){
// let aRect = a.getBoundingClientRect();
// let aX = aRect.x;
// return aX;
// //w console.log(aX);
//}
//
//function getLocationY(a){
// let aRect = a.getBoundingClientRect();
// let aY = aRect.y;
// return aY;
// // console.log(aY);
//}
function isCollide(a, b) {
let aRect = a.getBoundingClientRect();
let bRect = b.getBoundingClientRect();
return !(
(aRect.bottom < bRect.top) ||
(aRect.top > bRect.bottom) ||
(aRect.right < bRect.left) ||
(aRect.left > bRect.right)
)
}
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb';
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount && player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet';
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x + (player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y + (player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
function endGame() {
if (player.enemy) {
gameArea.removeChild(player.enemy);
}
gameArea.removeChild(player.plane);
if (player.bomb){
gameArea.removeChild(player.bomb);
player.bomb = null;
}
score.style.display = 'none';
scoreArea.style.display = 'none';
text.style.display = 'none';
gameMessage.style.display = 'inline-block';
player.inplay = false;
player.hasBomb = 0;
finalScore = document.createElement('div');
finalScore.classList.add('finalScore');
finalScore.innerHTML = 'YOU SCORED: ' + Math.floor(player.score);
gameArea.appendChild(finalScore);
player.games = 1;
player.getHit = 0;
}
function removeEnemy() {
gameArea.removeChild(player.enemy);
player.enemy = null;
player.score += 2000;
}
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
youre missing curly braces at the end of the if statement and i think its interpretting the next line as a part single line if statement
change to
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true) {
...
...
...
}
}

Change the Click Function to just Play

i have this 2 codes and want change the JS file.
Currently that's how it works:
--> the animation starts only when you click in the navigation.
I want play the animation if my site is loaded but i don't finde the function to change the code.
you can find the animation here: https://tympanus.net/Development/ShapeOverlays/index3.html
Thank you so much.
html:
<div class="animation">
<svg class="shape-overlays" viewBox="0 0 100 100" preserveAspectRatio="none">
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
</svg>
</div>
JS-File:
setTimeout(() => document.body.classList.add('render'), 60);
class ShapeOverlays {
constructor(elm) {
this.elm = elm;
this.path = elm.querySelectorAll('path');
this.numPoints = 2;
this.duration = 600;
this.delayPointsArray = [];
this.delayPointsMax = 0;
this.delayPerPath = 200;
this.timeStart = Date.now();
this.isOpened = false;
this.isAnimating = false;
}
toggle() {
this.isAnimating = true;
for (var i = 0; i < this.numPoints; i++) {
this.delayPointsArray[i] = 0;
}
if (this.isOpened === false) {
this.open();
} else {
this.close();
}
}
open() {
this.isOpened = true;
this.elm.classList.add('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
close() {
this.isOpened = false;
this.elm.classList.remove('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
*/
updatePath(time) {
const points = [];
for (var i = 0; i < this.numPoints; i++) {
const thisEase = this.isOpened ?
(i == 1) ? ease.cubicOut : ease.cubicInOut:
(i == 1) ? ease.cubicInOut : ease.cubicOut;
points[i] = thisEase(Math.min(Math.max(time - this.delayPointsArray[i], 0) / this.duration, 1)) * 100
}
let str = '';
str += (this.isOpened) ? `M 0 0 V ${points[0]} ` : `M 0 ${points[0]} `;
for (var i = 0; i < this.numPoints - 1; i++) {
const p = (i + 1) / (this.numPoints - 1) * 100;
const cp = p - (1 / (this.numPoints - 1) * 100) / 2;
str += `C ${cp} ${points[i]} ${cp} ${points[i + 1]} ${p} ${points[i + 1]} `;
}
str += (this.isOpened) ? `V 0 H 0` : `V 100 H 0`;
return str;
}
render() {
if (this.isOpened) {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * i)));
}
} else {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * (this.path.length - i - 1))));
}
}
}
renderLoop() {
this.render();
if (Date.now() - this.timeStart < this.duration + this.delayPerPath * (this.path.length - 1) + this.delayPointsMax) {
requestAnimationFrame(() => {
this.renderLoop();
});
}
else {
this.isAnimating = false;
}
}
}
Well, you missed last part
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
elmHamburger.addEventListener('click', () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
});
}());
There is event listener click attached to button elmHamburger, That is executing anonymous arrow function. If you want to run that animation on load, you need to replace click event with load.
That is:
elmHamburger.addEventListener('click', () => {...};
with
window.document.addEventListener('load', () => {...};
If you want to start animation on load and keep button event, then
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
const func = () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
}
elmHamburger.addEventListener('click', func);
window.addEventListener('load', func);
}());

Don't understand addEventListener behaviour

I have wrote this code in JavaScript :
window.onload = function() {
var keyboard = new Keyboard();
var gameCanvas = document.getElementById("gameCanvas").getContext("2d");
var player = new Player(gameCanvas, keyboard);
player.Init();
setInterval(function() {
gameCanvas.clearRect(0, 0, 1200, 300);
player.Update();
}, 20);
}
class Player {
constructor(canvas, keyboard) {
this._canvas = canvas;
this._keyboard = keyboard;
this._x = 100;
this._y = 75;
this._dx = 1;
this.dy = 1;
}
Init() {
this.Draw();
}
Update() {
if (this._keyboard.GetIsArrowLeftDown())
this._x -= this._dx;
if (this._keyboard.GetIsArrowRightDown())
this._x += this._dx;
if (this._keyboard.GetIsArrowUpDown())
this._y -= this._dy;
if (this._keyboard.GetIsArrowDownDown())
this._y += this._dy;
this.Draw();
}
Draw() {
this._canvas.beginPath();
this._canvas.arc(this._x, this._y, 50, 0, 2 * Math.PI);
this._canvas.closePath();
this._canvas.strokeStyle = "black";
this._canvas.stroke();
this._canvas.beginPath();
this._canvas.arc(this._x, this._y, 50, 0, 2 * Math.PI);
this._canvas.closePath();
this._canvas.fillStyle = "red";
this._canvas.fill();
}
}
class Keyboard {
constructor() {
this.isArrowLeftDown = false;
this.isArrowRightDown = false;
this.isArrowUpDown = false;
this.isArrowDownDown = false;
window.addEventListener("keyup", keyboard.OnKeyUpEvent);
window.addEventListener("keydown", keyboard.OnKeyDownEvent);
}
OnKeyUpEvent(event) {
if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key == "ArrowLeft")
this.isArrowLeftDown = false;
if (key == "ArrowRight")
this.isArrowRightDown = false;
if (key == "ArrowUp")
this.isArrowUpDown = false;
if (key == "ArrowDown")
this.isArrowDownDown = false;
}
OnKeyDownEvent(event) {
if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key == "ArrowLeft")
this.isArrowLeftDown = true;
if (key == "ArrowRight")
this.isArrowRightDown = true;
if (key == "ArrowUp")
this.isArrowUpDown = true;
if (key == "ArrowDown")
this.isArrowDownDown = true;
}
GetIsArrowLeftDown() {
return this.isArrowLeftDown;
}
GetIsArrowRightDown() {
return this.isArrowRightDown;
}
GetIsArrowUpDown() {
return this.isArrowUpDown;
}
GetIsArrowDownDown() {
return this.isArrowDownDown;
}
}
I have a Keyboard object which remembers which keys the user pressed.
Player is an object that draw himself.
I expected that when I press left, the shape would move to the left of the screen. But it's not working as expected.
It seems my keyboard object hasn't the good property values when read by the player object.
What am I missing?
Some issues:
In the Player constructor you assign 1 to the dy property, but it is later referenced as _dy, so you should add the underscore here.
In the Keyboard constructor you use keyboard, but that is undefined; you intended this.
In those same lines you pass a reference to the OnKeyUpEvent and OnKeyDownEvent methods. But when they are called, they do not pass the current value of this, so you should bind(this) to make that happen.
Here is the corrected code:
window.onload = function() {
var keyboard = new Keyboard();
var gameCanvas = document.getElementById("gameCanvas").getContext("2d");
var player = new Player(gameCanvas, keyboard);
player.Init();
setInterval(function() {
gameCanvas.clearRect(0, 0, 1200, 300);
player.Update();
}, 20);
}
class Player {
constructor(canvas, keyboard) {
this._canvas = canvas;
this._keyboard = keyboard;
this._x = 100;
this._y = 75;
this._dx = 1;
this._dy = 1; /// add the underscore
}
Init() {
this.Draw();
}
Update() {
if (this._keyboard.GetIsArrowLeftDown())
this._x -= this._dx;
if (this._keyboard.GetIsArrowRightDown())
this._x += this._dx;
if (this._keyboard.GetIsArrowUpDown())
this._y -= this._dy;
if (this._keyboard.GetIsArrowDownDown())
this._y += this._dy;
this.Draw();
}
Draw() {
this._canvas.beginPath();
this._canvas.arc(this._x, this._y, 50, 0, 2 * Math.PI);
this._canvas.closePath();
this._canvas.strokeStyle = "black";
this._canvas.stroke();
this._canvas.beginPath();
this._canvas.arc(this._x, this._y, 50, 0, 2 * Math.PI);
this._canvas.closePath();
this._canvas.fillStyle = "red";
this._canvas.fill();
}
}
class Keyboard {
constructor() {
this.isArrowLeftDown = false;
this.isArrowRightDown = false;
this.isArrowUpDown = false;
this.isArrowDownDown = false;
window.addEventListener("keyup", this.OnKeyUpEvent.bind(this)); // use this and bind
window.addEventListener("keydown", this.OnKeyDownEvent.bind(this));
}
OnKeyUpEvent(event) {
if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key == "ArrowLeft")
this.isArrowLeftDown = false;
if (key == "ArrowRight")
this.isArrowRightDown = false;
if (key == "ArrowUp")
this.isArrowUpDown = false;
if (key == "ArrowDown")
this.isArrowDownDown = false;
}
OnKeyDownEvent(event) {
if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key == "ArrowLeft")
this.isArrowLeftDown = true;
if (key == "ArrowRight")
this.isArrowRightDown = true;
if (key == "ArrowUp")
this.isArrowUpDown = true;
if (key == "ArrowDown")
this.isArrowDownDown = true;
}
GetIsArrowLeftDown() {
return this.isArrowLeftDown;
}
GetIsArrowRightDown() {
return this.isArrowRightDown;
}
GetIsArrowUpDown() {
return this.isArrowUpDown;
}
GetIsArrowDownDown() {
return this.isArrowDownDown;
}
}
<canvas id="gameCanvas"></canvas>
NB: You can detect such errors since they are reported in the console.

Categories