Change the Click Function to just Play - javascript

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);
}());

Related

TypeError: maze1.display is not a function

I have the mazeGen class that generates a maze using a version of prims algorithm using JS and P5.JS. Within the mazeGen class i have a display funtion that logs the maze to console. When i run this line it says it is not defined as a funtion. THe class will be used in another progect to generate multiple mazes to need it as a class
let maze1
function setup() {
maze1 = new MazeGen(11);
maze1.display()
}
function draw() {
background(220);
}
class MazeGen {
constructor(size) {
console.warn('in funt')
this.size = size
this.maze = new Array(this.size);
for (let i = 0; i < this.maze.length; i++) {
this.maze[i] = new Array(this.size);
for (let j = 0; j < this.maze.length; j++) {
this.maze[i][j] = 0
}
}
this.maze = this.PrimsAlgorithm()
this.maze[1][0] = 3;
this.maze[this.maze.length - 2][this.maze.length - 1] = 2;
console.table(this.maze);
return this.maze;
}
PrimsAlgorithm() {
this.frontAvailable = [0, 0, 0, 0];
this.currentCell = [1, 1];
while (this.Complete(this.maze, this.size) === false) {
//Console.WriteLine("Maze is not ready");
this.maze[this.currentCell[0]][this.currentCell[1]] = 1;
this.frontAvailable = this.Frontier(this.maze, this.currentCell);
//While the list of frontier cells is not empty
while (this.frontAvailable[0] !== 0 || this.frontAvailable[1] !== 0 || this.frontAvailable[2] !== 0 || this.frontAvailable[3] !== 0) {
//pick a random way
this.picked = false;
this.numSelected = 5;
while (this.picked === false) {
this.numSelected = Math.floor(Math.random() * 5);
if (this.frontAvailable[this.numSelected] === 1) {
this.picked = true;
}
}
//'Move to cell'
this.maze = this.MoveSquare();
this.frontAvailable = this.Frontier();
//Maze.PrintWhole(maze);
}
//List of frontier Cells is now empty
//Move to random cell and check if it is a path
this.currentCell = this.NewCurrent();
}
return this.maze;
}
Frontier() {
this.available = [0, 0, 0, 0];
//left check
if (((this.currentCell[1]) - 2) >= 0 && this.maze[this.currentCell[0]][(this.currentCell[1]) - 2] === 0) {
this.available[0] = 1;
} else {
this.available[0] = 0;
}
//up check
if (((this.currentCell[0]) - 2) >= 0 && this.maze[(this.currentCell[0]) - 2][(this.currentCell[1])] === 0) {
this.available[1] = 1;
} else {
this.available[1] = 0;
}
//right check
if (this.currentCell[1] + 2 < this.maze.length) {
if (this.maze[this.currentCell[0]][(this.currentCell[1]) + 2] === 0) {
this.available[2] = 1;
}
} else {
this.available[2] = 0;
}
//down check
if (this.currentCell[0] + 2 < this.maze.length) {
if (this.maze[this.currentCell[0] + 2][this.currentCell[1]] === 0) {
this.available[3] = 1;
}
} else {
this.available[3] = 0;
}
return this.available;
}
NewCurrent() {
this.found = false
this.currentCell = [];
while (this.found === false) {
this.cellX = Math.floor(Math.random() * (this.maze.length - 3) / 2)
this.cellX = this.cellX * 2 + 1
this.cellY = Math.floor(Math.random() * (this.maze.length - 3) / 2)
this.cellY = this.cellY * 2 + 1
if (this.maze[this.cellX][this.cellY] === 1) {
this.currentCell[0] = this.cellX;
this.currentCell[1] = this.cellY;
this.found = true
}
}
return this.currentCell;
}
MoveSquare() {
if (this.numSelected === 0) {
this.maze[this.currentCell[0]][(this.currentCell[1]) - 2] = 1;
this.maze[this.currentCell[0]][(this.currentCell[1]) - 1] = 1;
this.currentCell[1] = this.currentCell[1] - 2;
}
if (this.numSelected === 1) {
this.maze[(this.currentCell[0]) - 2][(this.currentCell[1])] = 1;
this.maze[(this.currentCell[0]) - 1][(this.currentCell[1])] = 1;
this.currentCell[0] = this.currentCell[0] - 2;
}
if (this.numSelected === 2) {
this.maze[this.currentCell[0]][(this.currentCell[1]) + 2] = 1;
this.maze[this.currentCell[0]][(this.currentCell[1]) + 1] = 1;
this.currentCell[1] = this.currentCell[1] + 2;
}
if (this.numSelected === 3) {
this.maze[(this.currentCell[0]) + 2][(this.currentCell[1])] = 1;
this.maze[(this.currentCell[0]) + 1][(this.currentCell[1])] = 1;
this.currentCell[0] = this.currentCell[0] + 2;
}
return this.maze;
}
Complete() {
let counter = 0;
//Console.WriteLine(counter);
for (let i = 0; i < (this.size - 1) / 2; i++) {
for (let j = 0; j < (this.size - 1) / 2; j++) {
let X = (2 * i) + 1;
let Y = (2 * j) + 1;
if (this.maze[X][Y] === 1) {
counter++;
}
}
}
return counter === (this.size - 1) / 2 * (this.size - 1) / 2;
}
display(){
console.table(this.maze);
}
}
If you return this.maze on constructor it will be an Array, Arrays don't have a display funcion
let maze1;
function setup() {
maze1 = new MazeGen(11);
maze1.display();
}
class MazeGen {
constructor(size) {
this.size = size;
this.maze = new Array(this.size).fill(1);
return this;//This is not really need it
}
display() {
console.log("In Display function");
console.log(this.maze);
}
}
setup();
The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.
More examples here : What does a JavaScript constructor return?
Are you trying to show the maze, or get what type of display it is on a webpage?
P5.js does not have such a method called .display(). However, there is a method called .show(), which makes the element visible. In normal web JavaScript, if you want to get or change the display type, you need to use the .style.display property.

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++
}
}

how to apply function to created table from localstorage

I'm making a gem-puzzle. I have a save button that after clicking on page reload shows the last saved state of the game. But when I reload the page, the table is rendered but the move click event doesn't work. How can this be fixed? What new arguments need to be passed to the function moveThisTile? Or should I save something else in localstorage? To explain my code: the startNewGame function is called to create the fifteen puzzle. showTable cycles through the two-dimensional array arrayForBoard and generates the necessary HTML for the fifteen puzzle board. moveThisTile takes two arguments that tell the program which tile of the fifteen puzzle needs to be moved
let moves = 0;
let table;
let rows;
let columns;
let textMoves;
let arrayForBoard;
let volumeOn = true;
function start() {
let button = document.getElementById('newGame');
button.addEventListener('click', startNewGame, false );
textMoves = document.getElementById('moves');
table = document.getElementById('table');
rows = 4;
columns = 4;
startNewGame();
}
function startNewGame() {
let arrayOfNumbers = new Array();
let arrayHasNumberBeenUsed;
let randomNumber = 0;
let count = 0;
moves = 0;
rows = document.getElementById('rows').value;
columns = document.getElementById('columns').value;
textMoves.innerHTML = moves;
arrayForBoard = new Array(rows);
for (let i = 0; i < rows; i++){
arrayForBoard[i] = new Array(columns);
}
arrayHasNumberBeenUsed = new Array( rows * columns );
for (let i = 0; i < rows * columns; i++){
arrayHasNumberBeenUsed[i] = 0;
}
for (let i = 0; i < rows * columns; i++){
randomNumber = Math.floor(Math.random()*rows * columns);
if (arrayHasNumberBeenUsed[randomNumber] == 0) {
arrayHasNumberBeenUsed[randomNumber] = 1;
arrayOfNumbers.push(randomNumber);
}else {
i--;
}
}
count = 0;
for (let i = 0; i < rows; i++){
for (let j = 0; j < columns; j++){
arrayForBoard[i][j] = arrayOfNumbers[count];
count++;
}
}
showTable();
}
let tbody = document.createElement('tbody');
document.querySelector('#table').appendChild(tbody);
function showTable() {
for (let tr of document.querySelectorAll("#table tr")) {
tr.remove();
}
for (let i = 0; i < rows; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++) {
let cell = document.createElement('td');
if (arrayForBoard[i][j] == 0) {
cell.className = 'blank';
} else {
cell.className = 'tile';
cell.draggable = true;
cell.addEventListener('click', () => {
moveThisTile(i, j);
if(volumeOn) {
sound()
}
})
cell.innerHTML =arrayForBoard[i][j];
}
tr.appendChild(cell);
}
tbody.appendChild(tr);
}
};
function moveThisTile(tableRow, tableColumn) {
if (checkIfMoveable(tableRow, tableColumn, 'up') ||
checkIfMoveable(tableRow, tableColumn, 'down') ||
checkIfMoveable(tableRow, tableColumn, 'left') ||
checkIfMoveable(tableRow, tableColumn, 'right') ) {
incrementMoves();
} else {
alert('ERROR: Cannot move tile!\nTile must be next to a blank space.');
}
if (checkIfWinner()) {
stopTimer();
alert(`Congratulations! You solved the puzzle in ${moves} moves and in ${document.querySelector('#timespan').innerText}.`);
startNewGame();
}
}
function checkIfMoveable(rowCoordinate, columnCoordinate, direction) {
let rowOffset = 0;
let columnOffset = 0;
if (direction == 'up') {
rowOffset = -1;
} else if (direction == 'down') {
rowOffset = 1;
} else if (direction == 'left') {
columnOffset = -1;
} else if (direction == 'right') {
columnOffset = 1;
}
if (rowCoordinate + rowOffset >= 0 && columnCoordinate + columnOffset >= 0 &&
rowCoordinate + rowOffset < rows && columnCoordinate + columnOffset < columns
) {
if ( arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] == 0) {
arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] = arrayForBoard[rowCoordinate][columnCoordinate];
arrayForBoard[rowCoordinate][columnCoordinate] = 0;
showTable();
return true;
}
}
return false;
}
document.querySelector('.save-btn').addEventListener('click', () => {
localStorage.setItem('currentGame', document.querySelector('tbody').innerHTML);
localStorage.setItem('currentMoves', document.querySelector('#moves').innerHTML);
localStorage.setItem('currentTime', document.querySelector('#timespan').innerHTML);
})
window.addEventListener('load', () => {
if(localStorage.getItem('currentGame') !== null) {
tbody.innerHTML = localStorage.getItem('currentGame');
document.querySelector('#moves').innerHTML = localStorage.getItem('currentMoves');
document.querySelector('#timespan').innerHTML = localStorage.getItem('currentTime');
} else {
start();
}
}, false );

a function within if else statement not working?

My function seem not to work and I am not sure why. It should return true or false but it doesnt. I am trying to calculate if the value is lower than 0 and if so return false, true otherwise.
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
checkforsales();
} else {
hundred = hundred + 100;
checkforsales();
}
}
}
console.log(tickets([25, 100]));
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
} else {
hundred = hundred + 100;
}
}
return checkforsales();
}
console.log(tickets([25, 100]));
You need to return checkforsales function as below
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
} else {
hundred = hundred + 100;
}
}
return checkforsales();
}

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) {
...
...
...
}
}

Categories