js only execute at a certain time? - javascript

i write this code to make a basic game. The full html is:
<!DOCTYPE>
<html>
<head>
<title>The dodge game</title>
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="index.css">
<script src="jquery.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="play-ground">
<div id="character"></div>
<div id="chaser"></div>
</div>
<button id="control-up" class="button">UP</button>
<button id="control-down" class="button">DOWN</button>
<button id="control-right" class="button">RIGHT</button>
<button id="control-left" class="button">LEFT</button>
</body>
</html>
the script :
$(document).ready (
function() {
var characterPositionLeft = 0;
var characterPositionTop = 0;
var chaserPositionLeft = 810;
var chaserPositionTop = 630;
var speed = 30;
var dspeed = 60;
var apoint = 5;
var testPositionLeft = function() {
if (chaserPositionLeft > characterPositionLeft) {
chaserPositionLeft -= 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionLeft);
} else if (chaserPositionLeft < characterPositionLeft) {
chaserPositionLeft += 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(characterPositionLeft);
}
}
var testPositionTop = function() {
if (chaserPositionTop > characterPositionTop) {
chaserPositionTop -= 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
} else if (chaserPositionTop < characterPositionTop) {
chaserPositionTop += 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
}
}
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
var TopCaught = false;
// up
$('#control-up').click (
function() {
testPositionTop();
if(characterPositionTop > 0) {
characterPositionTop -= speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached sky limit]');
}
}
)
// down
$('#control-down').click (
function() {
testPositionTop();
if(characterPositionTop < 630) {
characterPositionTop += speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached earth limit]');
}
}
)
// right
$('#control-right').click (
function() {
testPositionLeft();
if(characterPositionLeft < 810) {
characterPositionLeft += speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached right limit]');
}
}
)
// left
$('#control-left').click (
function() {
testPositionLeft();
if(characterPositionLeft > 0) {
characterPositionLeft -= speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached left limit]');
}
}
)
var leftRight = function() {
if(characterPositionLeft == CacLeftPlus || characterPositionLeft == CacLeftMinus) {
LeftCaught = true;
console.log('worked?');
} else {
}
}
var topBottom = function() {
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
TopCaught = true;
console.log('worked?');
} else {
}
}
var testEndGame = function () {
if (LeftCaught == true && TopCaught == true) {
console.log('game over');
alert('game over');
} else {
}
}
}
)
Everything works fine until the functions leftRight, upBottom and testEndGame. They only console worked when the console is logged 600 and 630. Can anyone please tell me the flaw in this code and a way to fix this? Here is the full code: http://jsfiddle.net/StK7r/1/

I believe you want
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
to instead test
if(characterPositionTop <= CacTopPlus && characterPositionTop >= CacTopMinus) {
because you intend your character to be caught inside a box. Same for left. Also, you were testing your 'top' position against your 'left'.
EDIT later:
I've updated the fiddle a bit. I noticed this also:
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
You are not updating these variables when chaserPositionTop/Left changes. They are being bound by value here, so obviously they remained forever at the value you are giving them in the initializer.

Related

How can I add a method for rotate the element automatically at page load?

In my index page I have a cube built with css and animated with js, at the moment I rotate the cube by clicking the mouse and drag. I want also at the load of page that the cube automatically rotate random slowly and at the click take the controll. How can I do that, after code my try:
var events = new Events();
events.add = function(obj) {
obj.events = { };
}
events.implement = function(fn) {
fn.prototype = Object.create(Events.prototype);
}
function Events() {
this.events = { };
}
Events.prototype.on = function(name, fn) {
var events = this.events[name];
if (events == undefined) {
this.events[name] = [ fn ];
this.emit('event:on', fn);
} else {
if (events.indexOf(fn) == -1) {
events.push(fn);
this.emit('event:on', fn);
}
}
return this;
}
Events.prototype.once = function(name, fn) {
var events = this.events[name];
fn.once = true;
if (!events) {
this.events[name] = [ fn ];
this.emit('event:once', fn);
} else {
if (events.indexOf(fn) == -1) {
events.push(fn);
this.emit('event:once', fn);
}
}
return this;
}
Events.prototype.emit = function(name, args) {
var events = this.events[name];
if (events) {
var i = events.length;
while(i--) {
if (events[i]) {
events[i].call(this, args);
if (events[i].once) {
delete events[i];
}
}
}
}
return this;
}
Events.prototype.unbind = function(name, fn) {
if (name) {
var events = this.events[name];
if (events) {
if (fn) {
var i = events.indexOf(fn);
if (i != -1) {
delete events[i];
}
} else {
delete this.events[name];
}
}
} else {
delete this.events;
this.events = { };
}
return this;
}
var userPrefix;
var prefix = (function () {
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1],
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
userPrefix = {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
};
})();
function bindEvent(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
function Viewport(data) {
events.add(this);
var self = this;
this.element = data.element;
this.fps = data.fps;
this.sensivity = data.sensivity;
this.sensivityFade = data.sensivityFade;
this.touchSensivity = data.touchSensivity;
this.speed = data.speed;
this.lastX = 0;
this.lastY = 0;
this.mouseX = 0;
this.mouseY = 0;
this.distanceX = 0;
this.distanceY = 0;
this.positionX = 1122;
this.positionY = 136;
this.torqueX = 0;
this.torqueY = 0;
this.down = false;
this.upsideDown = false;
this.previousPositionX = 0;
this.previousPositionY = 0;
this.currentSide = 0;
this.calculatedSide = 0;
bindEvent(document, 'mousedown', function() {
self.down = true;
});
bindEvent(document, 'mouseup', function() {
self.down = false;
});
bindEvent(document, 'keyup', function() {
self.down = false;
});
bindEvent(document, 'mousemove', function(e) {
self.mouseX = e.pageX;
self.mouseY = e.pageY;
});
bindEvent(document, 'touchstart', function(e) {
self.down = true;
e.touches ? e = e.touches[0] : null;
self.mouseX = e.pageX / self.touchSensivity;
self.mouseY = e.pageY / self.touchSensivity;
self.lastX = self.mouseX;
self.lastY = self.mouseY;
});
bindEvent(document, 'touchmove', function(e) {
if(e.preventDefault) {
e.preventDefault();
}
if(e.touches.length == 1) {
e.touches ? e = e.touches[0] : null;
self.mouseX = e.pageX / self.touchSensivity;
self.mouseY = e.pageY / self.touchSensivity;
}
});
bindEvent(document, 'touchend', function(e) {
self.down = false;
});
setInterval(this.animate.bind(this), this.fps);
}
events.implement(Viewport);
Viewport.prototype.animate = function() {
this.distanceX = (this.mouseX - this.lastX);
this.distanceY = (this.mouseY - this.lastY);
this.lastX = this.mouseX;
this.lastY = this.mouseY;
if(this.down) {
this.torqueX = this.torqueX * this.sensivityFade + (this.distanceX * this.speed - this.torqueX) * this.sensivity;
this.torqueY = this.torqueY * this.sensivityFade + (this.distanceY * this.speed - this.torqueY) * this.sensivity;
}
if(Math.abs(this.torqueX) > 1.0 || Math.abs(this.torqueY) > 1.0) {
if(!this.down) {
this.torqueX *= this.sensivityFade;
this.torqueY *= this.sensivityFade;
}
this.positionY -= this.torqueY;
if(this.positionY > 360) {
this.positionY -= 360;
} else if(this.positionY < 0) {
this.positionY += 360;
}
if(this.positionY > 90 && this.positionY < 270) {
this.positionX -= this.torqueX;
if(!this.upsideDown) {
this.upsideDown = true;
this.emit('upsideDown', { upsideDown: this.upsideDown });
}
} else {
this.positionX += this.torqueX;
if(this.upsideDown) {
this.upsideDown = false;
this.emit('upsideDown', { upsideDown: this.upsideDown });
}
}
if(this.positionX > 360) {
this.positionX -= 360;
} else if(this.positionX < 0) {
this.positionX += 360;
}
if(!(this.positionY >= 46 && this.positionY <= 130) && !(this.positionY >= 220 && this.positionY <= 308)) {
if(this.upsideDown) {
if(this.positionX >= 42 && this.positionX <= 130) {
this.calculatedSide = 3;
} else if(this.positionX >= 131 && this.positionX <= 223) {
this.calculatedSide = 2;
} else if(this.positionX >= 224 && this.positionX <= 314) {
this.calculatedSide = 5;
} else {
this.calculatedSide = 4;
}
} else {
if(this.positionX >= 42 && this.positionX <= 130) {
this.calculatedSide = 5;
} else if(this.positionX >= 131 && this.positionX <= 223) {
this.calculatedSide = 4;
} else if(this.positionX >= 224 && this.positionX <= 314) {
this.calculatedSide = 3;
} else {
this.calculatedSide = 2;
}
}
} else {
if(this.positionY >= 46 && this.positionY <= 130) {
this.calculatedSide = 6;
}
if(this.positionY >= 220 && this.positionY <= 308) {
this.calculatedSide = 1;
}
}
if(this.calculatedSide !== this.currentSide) {
this.currentSide = this.calculatedSide;
this.emit('sideChange');
}
}
this.element.style[userPrefix.js + 'Transform'] = 'rotateX(' + this.positionY + 'deg) rotateY(' + this.positionX + 'deg)';
if(this.positionY != this.previousPositionY || this.positionX != this.previousPositionX) {
this.previousPositionY = this.positionY;
this.previousPositionX = this.positionX;
this.emit('rotate');
}
}
var viewport = new Viewport({
element: document.getElementsByClassName('cube')[0],
fps: 20,
sensivity: .1,
sensivityFade: .93,
speed: 0.5,
touchSensivity: 1.5
});
function Cube(data) {
var self = this;
this.element = data.element;
this.sides = this.element.getElementsByClassName('side');
this.viewport = data.viewport;
// this.viewport.on('rotate', function() {
// self.rotateSides();
// });
// this.viewport.on('upsideDown', function(obj) {
// self.upsideDown(obj);
// });
this.viewport.on('sideChange', function() {
self.sideChange();
});
}
// Cube.prototype.rotateSides = function() {
// var viewport = this.viewport;
// if(viewport.positionY > 90 && viewport.positionY < 270) {
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + (viewport.positionX + viewport.torqueX) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + -(viewport.positionX + 180 + viewport.torqueX) + 'deg)';
// } else {
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + (viewport.positionX - viewport.torqueX) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + -(viewport.positionX + 180 - viewport.torqueX) + 'deg)';
// }
// }
// Cube.prototype.upsideDown = function(obj) {
// var deg = (obj.upsideDown == true) ? '180deg' : '0deg';
// var i = 5;
// while(i > 0 && --i) {
// this.sides[i].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + deg + ')';
// }
// }
Cube.prototype.sideChange = function() {
for(var i = 0; i < this.sides.length; ++i) {
this.sides[i].getElementsByClassName('cube-image')[0].className = 'cube-image';
}
this.sides[this.viewport.currentSide - 1].getElementsByClassName('cube-image')[0].className = 'cube-image active';
}
// Cube.prototype.autoMove = function() {
// var viewport = this.viewport;
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + Math.floor(Math.random() * 360) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + Math.floor(Math.random() * 360) + 'deg)';
// }
// this.autoMove();
new Cube({
viewport: viewport,
element: document.getElementsByClassName('cube')[0]
});
I tried to make something like this:
Viewport.prototype.autoMove = document.addEventListener('DOMContentLoaded', () => {
this.positionX = 0;
this.positionY = 0;
while (this.positionX <= 1122 && this.positionY <= 136) {
this.element.style[userPrefix.js + 'Transform'] = 'rotateX(' + this.positionY + 'deg) rotateY(' + this.positionX + 'deg)';
this.positionX++;
this.positionY++;
}
})
This is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./assets/css/style.css">
<title>Cube Project</title>
</head>
<body>
<h1 id="theTitle">CUBE</h1>
<div id="wrapper">
<div class="viewport">
<div class="cube">
<div class="side">
<div class="cube-image"><h2><a class="cube-link" href="#">BLA BLA BLA,<br> BLA BLA BLA.</a></h2></div>
</div>
<div class="side">
<div class="cube-image">2</div>
</div>
<div class="side">
<div class="cube-image">3</div>
</div>
<div class="side">
<div class="cube-image">4</div>
</div>
<div class="side">
<div class="cube-image">5</div>
</div>
<div class="side">
<div class="cube-image active">6</div>
</div>
</div>
</div>
</div>
<script src="./assets/js/app.js"></script>
</body>
</html>
Give an animation style to the cube element
#keyframes rotate{
to{ transform: rotate(360deg); }
}
.cube{
animation: rotate 4.5s linear infinite;
}
var randomMoves=serInterval(rotateRandomly,100);
function rotateRandomly() { ... }
on click:
if(randomMoves!=NULL) clearInterval(randomMoves);
randomMoves=NULL;
Of course you should use requestAnimationFrame instead, but this is so simple...

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

How to activate an interval when a certain position is reached?

The problem is that It calls the var intervalLeft and intervaRight at the same time. When it is moving right I want the intervalLeft not to work & vice versa.
When It reaches startPosition 100 it activates the intervalLeft and when it reaches startPosition 0 it activates intervalRight infinite.
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var intervalLeft = setInterval(frameLeft, 10);
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalRight);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.right = startPosition + "%";
}
}
}
</script>
This is the exercise:
Below this, you have a div that needs to move left to right using JS for the motion. Make it reach the end in 2 seconds, then return in 5s. Repeat that forever.
Have updated your code. Use below
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var rightTimer = true;
var leftTimer = false;
var intervalLeft;
function frameRight() {
if(!rightTimer){
rightTimer = true;
intervalRight = setInterval(frameRight,10)
return;
}
if (startPosition >= 100) {
rightTimer = false;
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if(!leftTimer){
leftTimer = true;
intervalLeft = setInterval(frameLeft,10)
return;
}
if (startPosition <= 0) {
leftTimer = false;
clearInterval(intervalLeft);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
After testing some more i've found the answer with fewer lines of code.
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10); //1
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
intervalLeft = setInterval(frameLeft, 10);
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalLeft);
intervalRight = setInterval(frameRight, 10);
} else {
startPosition -= 0.2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
this works how it Should. In the original code I posted the clearInterval was not linked to an actual intervalID

how to know if two objects are in the same position

I want to know if the first object is in the same position of the second object to alert a message.
I am trying to create a simple game to see if the falling object touches the object that I move with my keyboard to stop the game and write "game over".
var t = setInterval(move,50);
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
function move() {
var pob = parseInt(b.style.top);
if (pob + 30 >=350){
pob = 0;
var p = Math.floor(Math.random()*320);
b.style.left = p + "px";
}
pob += 10;
b.style.top=pob+"px";
var f = parseInt(b.style.top) ;
var box = parseInt(u.style.top);
if (f == box) {
alert("stop");
}
}
Something like this?
(Example from https://www.w3schools.com/graphics/game_obstacles.asp)
function touch(obj1,obj2) {
var myleft = obj1.offsetLeft;
var myright = obj1.offsetLeft+obj1.offsetWidth;
var mytop = obj1.offsetTop;
var mybottom = obj1.offsetTop+obj1.offsetHeight;
var otherleft = obj2.offsetLeft;
var otherright = obj2.offsetLeft+obj2.offsetWidth;
var othertop = obj2.offsetTop;
var otherbottom = obj2.offsetTop+obj2.offsetHeight;
return !((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright))
}
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
var s = document.getElementById('sep') ;
console.log(touch(b,u),touch(s,b))
<div id='ball'>b</div>
<div id='sep'>separator</div>
<div id='obj'>u</div>
EDIT:
And there is the full snippet:
var t = setInterval(move,50);
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
var pos = 10 ;
var posleft =100;
var divwidth = 300;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37) {
posleft = posleft - pos ;
if (posleft<0) {posleft = 0;}
u.style.left=posleft+'px';
}
else if(event.keyCode == 39) {
posleft = posleft + pos;
if (posleft>divwidth) {posleft = divwidth}
u.style.left=posleft+'px';
}
});
function touch(obj1,obj2) {
var myleft = obj1.offsetLeft;
var myright = obj1.offsetLeft+obj1.offsetWidth;
var mytop = obj1.offsetTop;
var mybottom = obj1.offsetTop+obj1.offsetHeight;
var otherleft = obj2.offsetLeft;
var otherright = obj2.offsetLeft+obj2.offsetWidth;
var othertop = obj2.offsetTop;
var otherbottom = obj2.offsetTop+obj2.offsetHeight;
return !((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright))
}
function move() {
if (touch(b,u)) {
alert("stop");
clearInterval(t)
}else{
var pob = parseInt(b.style.top);
if (pob + 30 >=200){
pob = 0;
var p = Math.floor(Math.random()*320);
b.style.left = p + "px";
}
pob += 5;
b.style.top=pob+"px";
}
}
<div id="obj" style="position:absolute;left:100px;top:180px;border:solid green 1px;">obj</div>
<div id="ball" style="position:absolute;top:0px;border:solid red 1px;">ball</div>
You need to focus on the page (click it) to control the game!
I hope that this will help you!

How to infinity spin on slot machine jQuery and stop it after do some action?

I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.

Categories