Flappy bird code not working - JavaScript - javascript

I wanted to write a flappy bird game in javascript but it doesn't seem to work when I open it in my browser. the css works.
lines 147, 154, 31 and 160 in js all seem to be errors, but I do not understand how to fix them.
this is my html:
var poles;
var bird;
var pole1;
var pole2;
var scoreSpan;
var speedSpan;
var speed;
var score;
var flapping;
var playing;
var scoreUpdated;
var gameArea;
var restartBtn;
var containerWidth;
var containerHeight;
function load() {
bird = document.getElementById("bird")
poles = document.getElementById("poles")
pole1 = document.getElementById("pole-1")
pole2 = document.getElementById("pole-2")
scoreSpan = document.getElementById("score")
speedSpan = document.getElementById("speed")
gameArea = document.getElementById("game-area");
restartBtn = document.getElementById("restart-btn");
containerWidth = gameArea.clientWidth;
containerHeight = gameArea.clientHeight;
}
function restart() {
restartBtn.removeEventListener('click', restart);
speed = 2;
score = 0;
scoreUpdated = false;
flapping = false;
playing = true;
speedSpan.textContent = speed;
scoreSpan.textContent = score;
poles.forEach((pole) => {
pole.style.right = 0;
});
bird.style.top = 20 + "%";
gameLoop();
}
function update() {
var polesCurrentPos = parseFloat(window.getComputedStyle(poles[0]).getPropertyValue("right"));
if (polesCurrentPos > containerWidth * 0.85) {
if (!scoreUpdated) {
score += 1;
scoreUpdated = true;
}
scoreSpan.textContent = score;
}
if (polesCurrentPos > containerWidth) {
var newHeight = parseInt(Math.random() * 100);
// ùéðåé âåáä îåè
pole1.style.height = 100 + newHeight + "px";
pole2.style.height = 100 - newHeight + "px";
polesCurrentPos = 0;
speed += 0.25;
speedSpan.textContent = parseInt(speed);
scoreUpdated = false;
}
poles.forEach((pole) => {
pole.style.right = polesCurrentPos + speed + "px";
});
let birdTop = parseFloat(window.getComputedStyle(bird).getPropertyValue("top"));
if (flapping) {
bird.style.top = birdTop + -2 + "px";
} else if (birdTop < containerHeight - bird.clientHeight) {
bird.style.top = birdTop + 2 + "px";
}
if (collision(bird, pole1) || collision(bird, pole2) || birdTop <= 0 || birdTop > containerHeight - bird.clientHeight) {
gameOver();
}
}
function gameOver() {
window.console.log("game over");
playing = false;
restartBtn.addEventListener('click', restart);
}
function gameLoop() {
update();
if (playing) {
requestAnimationFrame(gameLoop);
}
}
function collision(gameDiv1, gameDiv2) {
let left1 = gameDiv1.getBoundingClientRect().left;
let top1 = gameDiv1.getBoundingClientRect().top;
let height1 = gameDiv1.clientHeight;
let width1 = gameDiv1.clientWidth;
let bottom1 = top1 + height1;
let right1 = left1 + width1;
let left2 = gameDiv2.getBoundingClientRect().left;
let top2 = gameDiv2.getBoundingClientRect().top;
let height2 = gameDiv2.clientHeight;
let width2 = gameDiv2.clientWidth;
let bottom2 = top2 + height2;
let right2 = left2 + width2;
if (bottom1 < top2 || top1 > bottom2 || right1 < left2 || left1 > right2)
return false;
return true;
}
document.addEventListener("keydown", function (e) {
var key = e.key;
if (key === " " && playing) {
flapping = true;
}
});
document.addEventListener("keyup", function (e) {
e.preventDefault(); // Stops weird behaviour where releasing space calls restart()
var key = e.key;
if (key === " " && playing) {
flapping = false;
}
});
gameArea.addEventListener("mousedown", function (e) {
if (playing) {
flapping = true;
}
});
gameArea.addEventListener("mouseup", function (e) {
if (playing) {
flapping = false;
}
});
restart();
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Flappy Bird</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css" media="screen" />
<script src="game.js"></script>
</head>
<body onload="load();">
<div id="game">
<div id="game-area">
<div id="bird"></div>
<div class="pole" id="pole-1"></div>
<div class="pole" id="pole-2"></div>
</div>
<div id="game-info">
<p>Score:<span id="score">0</span></p>
<button id="restart-btn">Restart</button>
<p>Speed:<span id="speed">2</span></p>
</div>
</div>
</body>
</html>
There are many errors in the js when I run it and I can't seem to understand why. Does anyone know how to fix it?

One way to solve the problem is to move the event listeners into load and call load in your script:
var poles;
var bird;
var pole1;
var pole2;
var scoreSpan;
var speedSpan;
var speed;
var score;
var flapping;
var playing;
var scoreUpdated;
var gameArea;
var restartBtn;
var containerWidth;
var containerHeight;
function load() {
bird = document.getElementById("bird")
poles = document.querySelectorAll(".pole")
pole1 = document.getElementById("pole-1")
pole2 = document.getElementById("pole-2")
scoreSpan = document.getElementById("score")
speedSpan = document.getElementById("speed")
gameArea = document.getElementById("game-area");
restartBtn = document.getElementById("restart-btn");
containerWidth = gameArea.clientWidth;
containerHeight = gameArea.clientHeight;
gameArea.addEventListener("mousedown", function(e) {
if (playing) {
flapping = true;
}
});
gameArea.addEventListener("mouseup", function(e) {
if (playing) {
flapping = false;
}
});
}
function restart() {
restartBtn.removeEventListener('click', restart);
speed = 2;
score = 0;
scoreUpdated = false;
flapping = false;
playing = true;
speedSpan.textContent = speed;
scoreSpan.textContent = score;
poles.forEach((pole) => {
pole.style.right = 0;
});
bird.style.top = 20 + "%";
gameLoop();
}
function update() {
var polesCurrentPos = parseFloat(window.getComputedStyle(poles[0]).getPropertyValue("right"));
if (polesCurrentPos > containerWidth * 0.85) {
if (!scoreUpdated) {
score += 1;
scoreUpdated = true;
}
scoreSpan.textContent = score;
}
if (polesCurrentPos > containerWidth) {
var newHeight = parseInt(Math.random() * 100);
// ùéðåé âåáä îåè
pole1.style.height = 100 + newHeight + "px";
pole2.style.height = 100 - newHeight + "px";
polesCurrentPos = 0;
speed += 0.25;
speedSpan.textContent = parseInt(speed);
scoreUpdated = false;
}
poles.forEach((pole) => {
pole.style.right = polesCurrentPos + speed + "px";
});
let birdTop = parseFloat(window.getComputedStyle(bird).getPropertyValue("top"));
if (flapping) {
bird.style.top = birdTop + -2 + "px";
} else if (birdTop < containerHeight - bird.clientHeight) {
bird.style.top = birdTop + 2 + "px";
}
if (collision(bird, pole1) || collision(bird, pole2) || birdTop <= 0 || birdTop > containerHeight - bird.clientHeight) {
gameOver();
}
}
function gameOver() {
window.console.log("game over");
playing = false;
restartBtn.addEventListener('click', restart);
}
function gameLoop() {
update();
if (playing) {
requestAnimationFrame(gameLoop);
}
}
function collision(gameDiv1, gameDiv2) {
let left1 = gameDiv1.getBoundingClientRect().left;
let top1 = gameDiv1.getBoundingClientRect().top;
let height1 = gameDiv1.clientHeight;
let width1 = gameDiv1.clientWidth;
let bottom1 = top1 + height1;
let right1 = left1 + width1;
let left2 = gameDiv2.getBoundingClientRect().left;
let top2 = gameDiv2.getBoundingClientRect().top;
let height2 = gameDiv2.clientHeight;
let width2 = gameDiv2.clientWidth;
let bottom2 = top2 + height2;
let right2 = left2 + width2;
if (bottom1 < top2 || top1 > bottom2 || right1 < left2 || left1 > right2)
return false;
return true;
}
document.addEventListener("keydown", function(e) {
var key = e.key;
if (key === " " && playing) {
flapping = true;
}
});
document.addEventListener("keyup", function(e) {
e.preventDefault(); // Stops weird behaviour where releasing space calls restart()
var key = e.key;
if (key === " " && playing) {
flapping = false;
}
});
load();
restart();
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Flappy Bird</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css" media="screen" />
<script src="game.js" defer></script>
</head>
<body>
<div id="game">
<div id="game-area">
<div id="bird"></div>
<div class="pole" id="pole-1"></div>
<div class="pole" id="pole-2"></div>
</div>
<div id="game-info">
<p>Score:<span id="score">0</span></p>
<button id="restart-btn">Restart</button>
<p>Speed:<span id="speed">2</span></p>
</div>
</div>
</body>
</html>
I replaced poles = document.getElementById("poles") with poles = document.querySelectorAll(".pole") to find all poles.

Related

How to make JavaScript canvases overlap other canvases

var canvas = document.getElementById('PongPad1');
// var canvasSize = document.getElementById("PongPad1").style.height;
var PongPad1 = canvas.getContext('2d');
PongPad1.speed = 3;
PongPad1.w = 50;
PongPad1.h = 100;
PongPad1.x = "";
PongPad1.y = "";
if(PongPad1.x == ""){
PongPad1.x = 20;
}
if(PongPad1.y == ""){
PongPad1.y = 20;
}
function draw() {
PongPad1.fillStyle = 'black';
PongPad1.fillRect( PongPad1.x , PongPad1.y , PongPad1.w, PongPad1.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 38) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h)
if(PongPad1.y > 0){
PongPad1.y = PongPad1.y - PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 40) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h);
//Canvas hieght - PongPad1.h
if(PongPad1.y < 175){
PongPad1.y = PongPad1.y + PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
var canvas1 = document.getElementById('PongPad2');
// canvas.setAttribute('style', 'border: 1px solid; position: fixed; top: 8px; left: 8px; z-index: 0; width: 500px; height: 500px;');
var PongPad2 = canvas1.getContext('2d');
PongPad2.speed = 3;
PongPad2.w = 50;
PongPad2.h = 100;
PongPad2.x = "";
PongPad2.y = "";
if(PongPad2.x == ""){
PongPad2.x = window.innerWidth - (40 + PongPad2.w);
}
if(PongPad2.y == ""){
PongPad2.y = 20;
}
function draw2() {
PongPad2.fillStyle = 'black';
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 87) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h)
if(PongPad2.y > 0){
PongPad2.y = PongPad2.y - PongPad2.speed;
}
draw2();
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 83) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h);
//Canvas hieght - PongPad1.h
if(PongPad2.y < 175){
PongPad2.y = PongPad2.y + PongPad2.speed;
}
draw2();
}
});
var canvas2 = document.getElementById('ball');
var ball = canvas2.getContext('2d');
ball.speed = 1;
ball.w = 10;
ball.h = 10;
ball.dx = "";
ball.dy = "";
if(ball.dx == ""){
ball.dx = 1 * (Math.round(Math.random()) * 2 - 1);
}
if(ball.dy == ""){
ball.dy = 1 * (Math.round(Math.random()) * 2 - 1);
}
ball.x = "";
ball.y = "";
if(ball.x == ""){
ball.x = 960;
}
if(ball.y == ""){
ball.y = -300;
}
function draw3() {
ball.fillStyle = 'black';
ball.fillRect( ball.x , ball.y , ball.w, ball.h);
}
setInterval(() => {
ball.clearRect( ball.x , ball.y , ball.w, ball.h);
ball.x = ball.x + (ball.speed * ball.dx);
ball.y = ball.y + (ball.speed * ball.dy);
draw3();
if(ball.y < 0){
ball.dy = 1;
}
//Math.round(window.innerHeight/2)
if(ball.y > 200){
ball.dy = -1;
}
draw3();
if(ball.x > window.innerWidth){
ball.dx = -1;
ball.speed = 1;
}
if(ball.x < 0){
ball.dx = 1;
ball.speed = 1;
}
if(PongPad1.x < ball.x + ball.w &&
PongPad1.x + PongPad1.w > ball.x &&
PongPad1.y < ball.y + ball.h &&
PongPad1.y + PongPad1.h > ball.y)
{
ball.dx = 1;
//ball.speed++;
}
if(PongPad2.x < ball.x + ball.w &&
PongPad2.x + PongPad2.w > ball.x &&
PongPad2.y < ball.y + ball.h &&
PongPad2.y + PongPad2.h > ball.y)
{
ball.dx = -1;
//ball.speed++;
}
//console.log(ball.y);
}, 10);
var test = window.innerWidth ;
var test2 = window.innerHeight ;
document.getElementById("test").textContent = "" + test + "," + test2 + "";
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="Pangea 8 logo 3.png" type="image/x-icon">
<meta name="keywords" content="Pangea 8"/>
</head>
<style>
.work{
position: static;
border: 3px solid #73AD21;
}
</style>
<body id="body">
<p id ="test">
hello
</p>
<div >
<canvas class = "work" id="ball" height = "469px" width = "1900px" ></canvas>
<canvas class = "work" id="PongPad1" height = "275px" > </canvas>
<canvas class = "work" id="PongPad2" height = "275px" width = "1900px" ></canvas>
</div>
</body></html>
^ Is my Pong game. Use W,S and Up, Down to make the paddles appear. I made the canvases have a green border so you can see them better. I want these canvases to be on the same plane, instead of the 3. They are not in synch, I need them to be. How can I make them overlap so they are on the same level?
position:absolute;
top:0;
left:0;
this created my desired outcome.

How can i make the bullet not move with the character when looking either right or left?

I am having a problem where when I fire either left or right, once i move the character the bullets direction will change while its still fired. I am using the protagonist picture as the condition to either shoot right or left but i would like the bullet to keep firing in the fired direction even if i change the movement of the character
I am a beginner in Javascript and I'm using canvas to create a game for a college project.
if (moveBullet) {
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletX += 20;
}
if (s == "Protagenist_Left_Jet.png") {
bulletX -= 20;
}
if (bulletX >= canvas.width) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
if (bulletX <= 0) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
}
Full Code
<!DOCTYPE html>
<body>
<div id="canvasesdiv" style="text-align: center;">
<canvas id="canvas1" width="800" height="500" tabIndex="0" style="background: url('Level 1.png');position: relative; display: block;">
</div>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
//get the animation frame depending on the browser engine
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
//Hero Attributes
var jetPackAudio = new Audio();
jetPackAudio.src = "Jetpack Sound.mp3";
var heroPic = new Image();
var heroX ;
var heroY ;
//Decides where the hero is looking
var heroRight = false;
var life = 3;
var heroWidth = 50 ;
var heroHeight = 50 ;
var gravity = 5;
heroX = 20;
heroY = 440;
heroPic.src = "Protagenist_Stand_Jet.png";
function drawHero(x,y)
{
ctx.drawImage(heroPic,x,y,heroWidth,heroHeight);
}
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
// Key Attribute
var key = new Image();
key.src = "Key1.png"
var keyX ;
var keyY ;
var keyCounter = 0;
var keyWidth = 30 ;
var keyHeight = 30 ;
function drawKey()
{
ctx.drawImage(key,keyX,keyY,keyWidth,keyHeight);
}
var killCounter = 0 ;
var levelKillCounter;
// Monster 1 Attributes
var monster1 = new Image();
monster1.src = "Monster1_Left.png"
var m1MoveLeft = true;
var m1X ;
var m1Y ;
var m1Width = 50 ;
var m1Height = 50 ;
function drawMonster1()
{
ctx.drawImage(monster1,m1X,m1Y,m1Width,m1Height);
}
// Monster 2 Attributes
var monster2 = new Image();
monster2.src = "Monster 2_Right.png"
var m2MoveRight = true;
var m2X ;
var m2Y ;
var m2Width = 50 ;
var m2Height = 50 ;
function drawMonster2()
{
ctx.drawImage(monster2,m2X,m2Y,m2Width,m2Height);
}
// Monster 3 Attributes
var monster3 = new Image();
monster3.src = "Monster3_Right.png"
var m3MoveRight = true;
var m3X ;
var m3Y ;
var m3Width = 50 ;
var m3Height = 50 ;
function drawMonster3()
{
ctx.drawImage(monster3,m3X,m3Y,m3Width,m3Height);
}
// Hit Bottom
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
//Bullet Attribute
var bulletX;
var bulletY;
const ammo = [];
var moveBullet = false;
var bulletImage = new Image();
bulletImage.src = 'Bullet.png';
function drawBullet(x,y)
{
ctx.drawImage(bulletImage,bulletX,bulletY);
}
//this function is used to detect a hit monster 1
function getDistanceHit1() {
var xRect = (m1X - bulletX);
var yRect = (m1Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 2
function getDistanceHit2() {
var xRect = (m2X - bulletX);
var yRect = (m2Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 3
function getDistanceHit3() {
var xRect = (m3X - bulletX);
var yRect = (m3Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect if the player got the key
function getDistanceKey() {
var xRect = (keyX - heroX);
var yRect = (keyY - heroY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//configure the audio files
var fireAudio = new Audio();
fireAudio.src = "fire.mp3";
var hitAudio = new Audio();
hitAudio.src = "neck_snap.wav"
//Hero Movement
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
window.addEventListener("keydown", heroControl);
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
// 38 is up arrow, 87 is the W key
if (event.keyCode == 38 || event.keyCode == 87) { //Jump
upPressed = true;
console.log("HeroY = " + heroY);
}
// 39 is right arrow, 68 is thw D key
else if (event.keyCode == 39 || event.keyCode == 68) { //move Right
rightPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 37 || event.keyCode == 65) { // Move Left
leftPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 40 || event.keyCode == 83) { // Move Left
downPressed = true;
console.log("Heroy = " + heroY);
}
}
//Touch Controls
canvas.addEventListener("touchstart", handleTouchStart, false);
function handleTouchStart(touchEvent) { //event handler for touch events
var rect = canvas.getBoundingClientRect(); //to get canvas offsets
let touchX = touchEvent.changedTouches[0].clientX - rect.left;
let touchY = touchEvent.changedTouches[0].clientY - rect.top;
if (touchX <= canvas.width && touchX > canvas.width - 200) {
rightPressed = true;
}
if (touchX >= 0 && touchX < canvas.width - 600) {
leftPressed = true;
}
if (touchY >= 0 && touchY < canvas.height - 200) {
upPressed = true;
}
if (touchY <= canvas.height && touchY > canvas.height - 200) {
downPressed = true;
}
}
function moveHero() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(rightPressed) {
if(heroX < canvas.width - 53){
heroPic.src = "Protagenist_Right_Jet.png"
heroRight = true;
heroX = heroX + 10;
heroRight = true;
rightPressed = false;
}
else
{
rightPressed = false;
heroRight = false;
}
}
if(leftPressed) {
if(heroX > 0){
heroX = heroX - 10;
heroLeft = true;
heroPic.src = "Protagenist_Left_Jet.png";
bulletImage.src = "left_bullet.png";
leftPressed = false;
}
else
{
leftPressed = false;
heroLeft = false;
}
}
if(upPressed) {
if(heroY > 0){
heroY = heroY - 20;
heroStand = true;;
jetPackAudio.play();
heroPic.src = "Protagenist_Stand_Jet.png";
upPressed = false;
}
else
{
upPressed = false;
heroStand = false;;
}
}
if(downPressed) {
if(heroY < canvas.height){
heroPic.src = "Protagenist_Stand_Jet.png"
heroStand = true;
heroY = heroY + 10;
downPressed = false;
}
else
{
downPressed = false;
heroStand = false;
}
}
displayScoreArea();
drawHero(heroX,heroY);
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
requestAnimationFrame(moveHero);
}
//Level Setter
var level = 2;
function setLvl()
{
if(level == 1)
{
canvas.style = "background: url('Level 1.png')";
levelKillCounter = 3;
}
else if(level == 2)
{
canvas.style = "background: url('Level 2.png')";
monster1.src = "Monster3_Right.png"
monster2.src = "Monster3_Right.png"
}
else if(level == 3)
{
canvas.style = "background: url('Level 3.png')";
}
}
var gameAudio = new Audio();
gameAudio.src = "Dungeon Theme.mp3"
function animation()
{
setTimeout(() => {
//animation code goes into this anonymous function handler
requestAnimationFrame(animation);
//clear the whole canvas area
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveHero();
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
monsterAnimate();
setLvl();
heroY = heroY + gravity;
if(moveBullet)
{
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if(s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png")
{
bulletX +=20;
}
if(s == "Protagenist_Left_Jet.png")
{
bulletX -=20;
}
if(bulletX >= canvas.width)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
if(bulletX <= 0)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
console.log(getDistanceHit1());
if (getDistanceHit1() <= 30 ||
getDistanceHit2() <= 30 ||
getDistanceHit3() <= 30 )
{
//Delete Monster
if(getDistanceHit1() <= 30)
{
m1X = 1000;
m1Y = 1000;
}
if(getDistanceHit2() <= 30)
{
m2X = 1000;
m2Y = 1000;
}
if(getDistanceHit3() <= 30)
{
m3X = 1000;
m3Y = 1000;
}
//increase the hit count
killCounter++;
//we have a hit
moveBullet = false;
//play the hitAudio
hitAudio.play();
//Reset Bullet
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
}
if(killCounter == 3)
{
keyX = canvas.width / 2;
keyY = 150;
}
if(getDistanceKey() <= 10)
{
keyCounter = 1;
keyX = 1000;
keyY = 1000;
}
//level progression flow - check of level objectives are met
if (level == 1 && keyCounter == 1 && heroX >= 700 & heroY >= 50) {
alert("Level 1 completed. Starting Level 2...");
level = 2;
killCounter = 0; //reset
keyCounter = 0;//reset
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
}
else if (level == 2 && keyCounter == 1 && heroX == 700 & heroY == 50) {
alert("Level 2 completed. Starting Level 3...");
level = 3;
killCounter = 0; //reset
keyCounter = 0;//reset
}
else if (level == 3 && currentLevelHits == 4) {
//last level
var playAgain = confirm("Game completed. Play again?");
if (playAgain)
window.location.reload(true); //force reload
else
stopAnimation = true;
}
//gameAudio.play();
displayScoreArea();
hitBottom();
},100)
}
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
function monsterAnimate()
{
//Movement for level 1
if(level == 1)
{
if(m1MoveLeft)
{
m1X -= 10
}
else if(!m1MoveLeft)
{
m1X += 10
}
if(m2MoveRight)
{
m2X += 10
}
else if(!m2MoveRight)
{
m2X -= 10
}
if(m3MoveRight)
{
m3X +=10
}
else if(!m3MoveRight)
{
m3X -= 10
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 310)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 310)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
//Movement for level 2
if(level == 2)
{
if(m1MoveLeft)
{
m1X -= 20
}
else if(!m1MoveLeft)
{
m1X += 20
}
if(m2MoveRight)
{
m2X += 20
}
else if(!m2MoveRight)
{
m2X -= 20
}
if(m3MoveRight)
{
m3X +=20
}
else if(!m3MoveRight)
{
m3X -= 20
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 600)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 500)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
}
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", "black");
gradient.addColorStop("0.5", "red");
gradient.addColorStop("1.0", "white");
//Draw Score Area
function displayScoreArea() {
ctx.font = "40px Arial";
ctx.strokeStyle = gradient;
ctx.fillStyle = gradient;
ctx.strokeText(killCounter, 380, 60);
ctx.strokeText(life, 65, 45);
ctx.strokeText(keyCounter, 65, 90);
}
animation();
function moveup()
{
upPressed = true;
}
function movedown()
{
downPressed = true;
}
function moveright()
{
rightPressed = true;
}
function moveleft()
{
leftPressed = true;
}
function shootGun()
{
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
</script>
<div style="text-align:center;width:900px;">
<button style="width: 100px; height: 60px;" onclick="moveup()">UP</button><br><br>
<button style="width: 100px; height: 60px;" onclick="moveleft()">LEFT</button>
<button style="width: 100px; height: 60px; margin-left: 20px;" onclick="moveright()">RIGHT</button><br><br>
<button style="width: 100px; height: 60px;" onclick="movedown()">DOWN</button>
<button style="width: 100px; height: 60px;" onclick="shootGun()">SHOOT</button>
</div>
</body>
</html>
Using objects would be one (of many) steps in the right direction. Even without them, you could:
In your bullet variable creation
...
//Bullet Attribute
let bulletX;
let bulletY;
let bulletVelocity;
...
In your hero control function, where the firing action currently takes place, initialize your bullet properties once
...
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
// Initialize bullet velocity
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletVelocity = 20;
} else {
bulletVelocity = -20;
}
...
In your animation function, where this currently takes place, update your bullet position according to its velocity
...
if (moveBullet) {
bulletX += bulletVelocity;
if (bulletX >= canvas.width) {
...
There are lots of things I would refactor in your current setup, but this should get you moving on your current problem.
And a quick example of a very simple object:
// create with key: value pairs
let bullet = {
x: 0,
y: 0,
velocity: 0,
};
// Access or set properties using dot notation
bullet.x = heroX + 10;
bullet.y = heroY + (heroHeight / 2);

Making an HTML button disappear when clicked through javascript

I am working on a creating a video game, and I want a button to disappear once I click it and move onto the next screen. I can set the function of the button through my html and js file, but I am not sure how to make it disappear once clicked.
My HTML code:
<html>
<head>
<title> Pong </title>
<link type = "text/css" href = "main.css" rel = "stylesheet">
</head>
<canvas id="gameCanvas" width="1350" height="600"></canvas>
<body>
<button id = 'easy_click' onclick="EasyChange()"> Easy </button>
<button id = 'int_change' onclick="intChange()"> Intermediate </button>
<button id = "hard_change" onclick="hardChange()"> Hard </button>
</body>
<script src = "functions.js"></script>
</html>
Here is my JS code:
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 20;
var ballSpeedY = 10
var menuScreen = false;
var name = "Developed by Jonah Johnson";
var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 10;
var easybutton = "Easy";
var hardButton = "Hard";
var intButton = "Intermediate";
var diffLevelEasy = false;
var diffLevelMedium = true;
var diffLevelHard = false;
var showingWinScreen = true;
var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;
function calculateMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
//changing of difficulty
//easy changing
function EasyChange() {
diffLevelEasy = true;
diffLevelMedium = false;
diffLevelHard = false;
showingWinScreen = false;
}
function intChange() {
diffLevelEasy = false;
diffLevelMedium = true;
diffLevelHard = false;
showingWinScreen = false;
}
function hardChange() {
diffLevelEasy = false;
diffLevelMedium = false;
diffLevelHard = true;
showingWinScreen = false;
}
function handleMouseClick(evt) {
if(showingWinScreen) {
player1Score = 0;
player2Score = 0;
showingWinScreen = false;
}
}
// getting an easy medium
function handleMouseClick(evt) {
if(easybutton) {
diffLevelEasy = true;
diffLevelMedium = false;
diffLevelHard = false;
showingWinScreen = false;
}
}
//getting medium
function handleMouseClick(evt) {
if(intButton) {
diffLevelEasy = false;
diffLevelMedium = true;
diffLevelHard = false;
showingWinScreen = false;
}
}
//getting hard
function handleMouseClick(evt) {
if(hardButton) {
diffLevelEasy = false;
diffLevelMedium = false;
diffLevelHard = true;
showingWinScreen = false;
}
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 30;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/framesPerSecond);
canvas.addEventListener('mousedown', handleMouseClick);
canvas.addEventListener('mousemove',
function(evt) {
var mousePos = calculateMousePos(evt);
paddle1Y = mousePos.y - (PADDLE_HEIGHT/2);
});
}
function ballReset() {
if(player1Score >= WINNING_SCORE ||
player2Score >= WINNING_SCORE) {
showingWinScreen = true;
}
ballSpeedX = -ballSpeedX;
ballX = canvas.width/2;
ballY = canvas.height/2;
}
function computerMovement() {
/// ai movement
//easy
if(diffLevelEasy === true) {
var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY - 35) {
paddle2Y = paddle2Y + 2;
} else if(paddle2YCenter > ballY + 35) {
paddle2Y = paddle2Y - 2;
}
}
//medium
else if(diffLevelMedium === true) {
var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY - 35) {
paddle2Y = paddle2Y + 12;
} else if(paddle2YCenter > ballY + 35) {
paddle2Y = paddle2Y - 12;
}
}
//hard
else if(diffLevelHard === true) {
var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY - 35) {
paddle2Y = paddle2Y + 18;
} else if(paddle2YCenter > ballY + 35) {
paddle2Y = paddle2Y - 18;
}
}
}
function moveEverything() {
if(showingWinScreen) { //showing win screen
return;
}
computerMovement();
ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY;
if(ballX < 0) {
if(ballY > paddle1Y &&
ballY < paddle1Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
var deltaY = ballY
-(paddle1Y+PADDLE_HEIGHT/2);
ballSpeedY = deltaY * 0.35;
} else {
player2Score++; // must be BEFORE ballReset()
ballReset();
}
}
if(ballX > canvas.width) {
if(ballY > paddle2Y &&
ballY < paddle2Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
var deltaY = ballY
-(paddle2Y+PADDLE_HEIGHT/2);
ballSpeedY = deltaY * 0.35;
} else {
player1Score++; // must be BEFORE ballReset()
ballReset();
}
}
if(ballY < 0) {
ballSpeedY = -ballSpeedY;
}
if(ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
}
function drawNet() {
for(var i=0;i<canvas.height;i+=40) {
colorRect(canvas.width/2-1,i,2,20,'white');
}
}
function drawEverything() {
// next line blanks out the screen with black
colorRect(0,0,canvas.width,canvas.height,'black');
if(showingWinScreen) {
canvasContext.fillStyle = 'white';
if(player1Score >= WINNING_SCORE) {
canvasContext.fillText("Left Player Won", 350, 200);
} else if(player2Score >= WINNING_SCORE) {
canvasContext.fillText("Right Player Won", 350, 200);
}
canvasContext.fillText("click to continue", 350, 500);
canvasContext.fillText("Difficulty:", 50, 50);
canvasContext.fillText(easybutton, 50, 100);
canvasContext.fillText(intButton, 50, 200);
canvasContext.fillText(hardButton, 50, 300);
return;
}
drawNet();
// this is left player paddle
colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');
// this is right computer paddle
colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');
// next line draws the ball
colorCircle(ballX, ballY, 10, 'white');
canvasContext.fillText(player1Score, 100, 100);
canvasContext.fillText(player2Score, canvas.width-100, 100);
canvasContext.fillText(name, 100, 590);
}
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
canvasContext.fill();
}
function colorRect(leftX,topY, width,height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX,topY, width,height);
}
//sets how hard the game is
if(diffLevel = diffLevelEasy) {
var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY - 35) {
paddle2Y = paddle2Y + 2;
} else if(paddle2YCenter > ballY + 35) {
paddle2Y = paddle2Y - 2;
}
}
I am just trying to make the button delete when clicked, so how do I do that?
Found this on web try it
<input type="button" id="toggler" value="Toggler" onClick="action();" />
<input type="button" id="togglee" value="Togglee" />
<script>
var hidden = false;
function action() {
hidden = !hidden;
if(hidden) {
document.getElementById('togglee').style.visibility = 'hidden';
} else {
document.getElementById('togglee').style.visibility = 'visible';
}
}
</script>
Just call evt.target.remove() and it will remove it from the DOM.
For future scalability and probably, maintainability and with minimum code changes, I'd send the button as an argument to the event handler:
<button id = 'easy_click' onclick="EasyChange(this)"> Easy </button>
<button id = 'int_change' onclick="intChange(this)"> Intermediate </button>
<button id = "hard_change" onclick="hardChange(this)"> Hard </button>
Then set the style in the handler function:
function EasyChange(btn) {
diffLevelEasy = true;
diffLevelMedium = false;
diffLevelHard = false;
showingWinScreen = false;
btn.style.display='none';
}
function intChange(btn) {
diffLevelEasy = false;
diffLevelMedium = true;
diffLevelHard = false;
showingWinScreen = false;
btn.style.display='none';
}
function hardChange(btn) {
diffLevelEasy = false;
diffLevelMedium = false;
diffLevelHard = true;
showingWinScreen = false;
btn.style.display='none';
}
To restore the button use:
btn.style.display='none';
Alternatively, to stop the DOM jumping about use:
btn.style.visibility='hidden';
and
btn.style.visibility='visible';
Also let me know when and where it's published because web pong sounds awesome.

Add links to images in array

I'm trying to add links to the images in my JS array so that, when clicked, they direct you to a info page.
I tried to use the following code but the images won't show.
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com"],
['work/02.png',"http://www.stackoverflow.com"],
['work/03.png',"http://www.stackoverflow.com"],
['work/04.png',"http://www.stackoverflow.com"]);
If I remove the links the images do show.
I'm using a variation of this code: http://bouncingdvdlogo.com/
Here is my full code:
var width = 400;
var height = 400;
var swoosh = 4;
var stopafter=0; //set time in seconds before image disappears. Use 0 for never
var maxswoosh = 50;
var xMax;
var yMax;
var xPos = 0;
var yPos = 0;
var xDir = 'right';
var yDir = 'down';
var screenSavouring = true;
var tempswoosh;
var newXDir;
var newYDir;
function setupShit() {
if (document.all) {
xMax = document.body.clientWidth
yMax = document.body.clientHeight
document.all("work").style.visibility = "visible";
}
else if (document.layers||document.getElementById) {
xMax = window.innerWidth-0;
yMax = window.innerHeight;
if (document.getElementById)
document.getElementById("work").style.visibility="visible"
else
document.layers["work"].visibility = "show";
}
setTimeout('moveIt()',500);
}
function moveIt() {
if (screenSavouring == true) {
calculatePosition();
if (document.all) {
document.all("work").style.left = xPos + document.body.scrollLeft;
document.all("work").style.top = yPos + document.body.scrollTop;
}
else if (document.layers) {
document.layers["work"].left = xPos + pageXOffset;
document.layers["work"].top = yPos + pageYOffset;
}
else if (document.getElementById) {
document.getElementById("work").style.left = xPos + pageXOffset;
document.getElementById("work").style.top = yPos + pageYOffset;
}
doit=setTimeout('moveIt()',30);
}
}
function calculatePosition() {
if (xDir == "right") {
if (xPos > (xMax - width - swoosh)) {
xDir = "left";
cC();
}
}
else if (xDir == "left") {
if (xPos < (0 + swoosh)) {
xDir = "right";
cC();
}
}
if (yDir == "down") {
if (yPos > (yMax - height - swoosh)) {
yDir = "up";
cC();
}
}
else if (yDir == "up") {
if (yPos < (0 + swoosh)) {
yDir = "down";
cC();
}
}
if (xDir == "right") {
xPos = xPos + swoosh;
}
else if (xDir == "left") {
xPos = xPos - swoosh;
}
else {
xPos = xPos;
}
if (yDir == "down") {
yPos = yPos + swoosh;
}
else if (yDir == "up") {
yPos = yPos - swoosh;
}
else {
yPos = yPos;
}
}
if (document.all||document.layers||document.getElementById){
window.onload = setupShit;
window.onresize = new Function("window.location.reload()");
}
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/02.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/03.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/04.png',"http://www.stackoverflow.com", "Your text goes here"]);
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
var currentImage = 0
function cC() {
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
Thanks!
Try replacing your for loop with below
for(i=0; i<nelements; i++) {
preload_image_object.src = WorkArray[i][0];
}
Also Replace function cC() with below:
function cC() {
var nelements = WorkArray.length;
var rdmnum = Math.floor(Math.random() * nelements);
var currentImage = rdmnum++;
if (currentImage == nelements) {
rdmnum = Math.floor(Math.random() * nelements);
}
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage = "url('" + WorkArray[currentImage][0] + "')";
}

appending images using easeljs and javascript for snake game

This is index.html file.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dragon Progression</title>
<script type="text/javascript" src="library/easeljs-0.6.0.min.js"></script>
<script type="text/javascript" src="libs/ndgmr.Collision.js"></script>
<script type="text/javascript" src="js/startScreen.js"></script>
<script type="text/javascript" src="js/gameScreen.js"></script>
</head>
<body onLoad="renderStartScreen()">
<canvas id="canvas1" width="1024" height="698">
Browser does not support canvas. Please upgrade browser.
</canvas>
</body> </html>
This is StartScreen.js
var introBackground;
var startScreenBtn;
var startScreenBtnImg;
var stage;
var stageHeight;
var stageWidth;
//this function render start screen
function renderStartScreen()
{
stage = new createjs.Stage("canvas1");
stage.enableMouseOver();
stageWidth = document.getElementById("canvas1").width;
stageHeight = document.getElementById("canvas1").height;
introBackground = new createjs.Bitmap("assets/images/bg.jpg");
introBackground.x = introBackground.y = 0;
stage.addChild(introBackground);
startScreenBtn = new createjs.Container();
startScreenBtn.x = 500;
startScreenBtn.y = 300;
startScreenBtnImg = new createjs.Bitmap("assets/images/start_button_normal.png");
stage.addChild(startScreenBtn);
startScreenBtn.addChild(startScreenBtnImg);
var btnBg = new createjs.Shape();
btnBg.graphics.beginFill("#FFFFFF");
btnBg.graphics.drawRect(0, 0, 143, 35);
btnBg.alpha = 0.01;
startScreenBtn.addChild(btnBg);
startScreenBtn.addEventListener("mouseover", onstartScreenBtnOver);
startScreenBtn.addEventListener("mouseout", onstartScreenBtnOut);
startScreenBtn.addEventListener("click", onstartScreenBtnClick);
createjs.Ticker.setFPS(45);
createjs.Ticker.addEventListener("tick", startScreenTickHandler);
}
//event handler function get called on start button roll over
function onstartScreenBtnOver()
{
startScreenBtnImg.image.src = "assets/images/start_button_over.png";
}
//event handler function get called on start button roll out
function onstartScreenBtnOut()
{
startScreenBtnImg.image.src = "assets/images/start_button_normal.png";
}
//event handler function get called on start button click
function onstartScreenBtnClick(event)
{
cleanupStartScreen();
}
//event handler function get called on specified interval
function startScreenTickHandler()
{
stage.update();
}
//clean start screen and loads main game
function cleanupStartScreen()
{
stage.removeAllChildren();
stage.update();
stage.removeAllEventListeners();
createjs.Ticker.removeEventListener("tick", startScreenTickHandler);
loadMainGame();
}
This is gamescreen.js file.
var background;
var snakeArray = [];
//var snakeBody;
var snake;
var snakeWidth=25;
var food;
var keyCode;
var CHECK_HIT_ALPHA = 1;
var currDirection;
var tempX;
var tempY;
var prevX;
var prevY;
function loadMainGame()
{
background = new createjs.Bitmap("assets/images/loading_background.jpg");
background.x=0;
background.y=0;
//snake = new createjs.Container();
//snakeTail = new createjs.Shape();
//snakeTail.graphics.beginFill("#E2DC1E").drawPolyStar(40,65,15,3,0,360);
createSnakeHead();
createFood();
snakeArray.currDirection = "";
stage.addChild(background,snake,food);
createjs.Ticker.addEventListener("tick", snakeMovement);
//createjs.Ticker.addEventListener("tick", snakeBodyMovement);
window.onkeydown=function(e)
{
keyCode = e.keyCode || e.which || window.Event;
if(keyCode == 37 && currDirection != "right")
{
currDirection = "left";
snake.rotation= -90;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 39 && currDirection !="left")
{
currDirection = "right";
snake.rotation = 90;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 38 && currDirection != "down")
{
currDirection = "up";
snake.rotation = 360;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 40 && currDirection != "up")
{
currDirection = "down";
snake.rotation = 180;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
}
}
function createSnakeHead()
{
snake = new createjs.Bitmap("assets/images/snake.png");
snake.type = "head";
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
snake.x = randX;
snake.y = randY;
snake.regX = snake.image.width/2;
snake.regY = snake.image.height/2;
snakeArray.push(snake);
}
function createFood()
{
food = new createjs.Bitmap("assets/images/food.png");
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
food.x = randX;
food.y = randY;
}
function snakeMovement()
{
console.log(snakeArray.length);
for(var i=0;i<=snakeArray.length-1;i++)
{
if(currDirection=="left")
{
snakeArray[i].rotation= -90;
snakeArray[i].x = snakeArray[i].x - 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if (snakeArray[i].x <= 0)
{
snakeArray[i].x = stageWidth;
}
snakeBodyMovement(prevX,prevY);
}
else if(currDirection == "right")
{
//tempX = snakeArray[0].x;
snakeArray[i].rotation= 90;
snakeArray[i].x = snakeArray[i].x + 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if (snakeArray[i].x >= stageWidth)
{
snakeArray[i].x = 0;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "right";
}
else if(currDirection == "up")
{
//tempY = snakeArray[0].y;
snakeArray[i].rotation= 360;
snakeArray[i].y = snakeArray[i].y - 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if(snakeArray[i].y <=0)
{
snakeArray[i].y = stageHeight;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "up";
}
else if(currDirection == "down")
{
//var tempY = snakeArray[0].y;
snakeArray[i].rotation= 180;
snakeArray[i].y = snakeArray[i].y + 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if(snakeArray[i].y >= stageHeight)
{
snakeArray[i].y = 0;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "down";
}
}
foodSnakeCollision();
stage.update();
}
function foodSnakeCollision()
{
var intersection = ndgmr.checkPixelCollision(snake,food,CHECK_HIT_ALPHA);
if(intersection)
{
console.log("Eat food");
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
food.x = randX;
food.y = randY;
createSnake();
}
}
function createSnake()
{
var snakeBody = new createjs.Bitmap("assets/images/snake.png");
snakeBody.type = "body";
snakeBody.regX = snake.image.width/2;
snakeBody.regY = snake.image.height/2;
if(currDirection=="left")
{
snakeBody.x = snakeArray[snakeArray.length-1].x + 25;
snakeBody.y =snakeArray[snakeArray.length-1].y +0;
}
if(currDirection == "right")
{
snakeBody.x = snakeArray[snakeArray.length-1].x - 25;
snakeBody.y =snakeArray[snakeArray.length-1].y - 0;
}
if(currDirection == "up")
{
snakeBody.x = snakeArray[snakeArray.length-1].x + 0;
snakeBody.y =snakeArray[snakeArray.length-1].y + 25;
}
if(currDirection == "down")
{
snakeBody.x = snakeArray[snakeArray.length-1].x - 0;
snakeBody.y =snakeArray[snakeArray.length-1].y - 25;
}
snakeArray.push(snakeBody);
console.log(snakeArray.length + "after collision");
stage.addChild(snakeBody);
}
function snakeBodyMovement(prevX,prevY)
{
for(var i=1;i<=snakeArray.length-1;i++)
{
if(currDirection == "left")
{
snakeArray[i].x = prevX + 15;
snakeArray[i].y = prevY;
}
else if(currDirection == "right")
{
snakeArray[i].x = prevX - 15;
snakeArray[i].y = prevY;
}
else if(currDirection == "up")
{
snakeArray[i].x = prevX;
snakeArray[i].y = prevY + 15;
}
else if(currDirection == "down")
{
snakeArray[i].x = prevX;
snakeArray[i].y = prevY - 15;
}
}
}
in gameScreen.js file,the new snakebody that i add using snakebody is not appending one after the other. It is adding one below the other.Please suggest how do i smoothly move the snake body and the additional snake parts that gets added once it collides with the food.
I think the root of your problem here is that you aren't preloading your images. Consider your code block from GameScreen.js
snake = new createjs.Bitmap("assets/images/snake.png");
snake.type = "head";
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
snake.x = randX;
snake.y = randY;
console.log("Snake head width: " + snake.image.width);
snake.regX = snake.image.width/2;
snake.regY = snake.image.height/2;
The image isn't loaded from the server until the declaration of the Bitmap is made. Because loading images is asynchronous, your image won't necessarily be loaded by the time it hits the line snake.regX = snake.image.width/2; and the width and height will both be 0. You can confirm this by looking at the console log I have added. With your registration points off, all your positioning will be off as well.
My suggestion would be to use the preloadjs library that is part of the createjs suite to preload your images. http://www.createjs.com/Docs/PreloadJS/modules/PreloadJS.html.

Categories