Making an HTML button disappear when clicked through javascript - 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.

Related

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

Game score counter

I'm new to programming and I tried to make a game. You move a red block and when you hit a green block the you go back to (0,0) and the green block goes to a random location.
Now my question is how do I put a score counter in the game when I hit the green block that it counts +1.
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
document.onkeydown = anim;
window.onload=startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<button onmousedown="anim(e)" onmouseup="clearmove()" ontouchstart="moveup()">Start</button>
<br><br>
<p>press start to start
<br> use the buttons ↑ ↓ → ← on your keyboard to move stop with the space</p>
Changes
Added an <output> tag to display score.
Redefined event handlers/listeners
Details on changes are commented in demo
Demo
// Reference output#score
var score = document.getElementById('score');
// Declare points
var points = 0;
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
// Convert points to a real number
points = parseInt(points, 10);
// Increment points
points++;
// Set output#score value to points
score.value = points;
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
/* Set on click handler
|| When event occurs call startGame() / exclude
|| parenthesis
*/
document.onclick = startGame;
/* Register keydown event
|| When event occurs call anim() / exclude parenthesis
*/
document.addEventListener('keydown', anim, false);
/* When a callback is a named function / exclude the
|| parenthesis
*/
window.onload = startGame;
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
button {
font: inherit;
}
<br><br>
<button id='start'>Start</button>
<br><br>
<label for='score'>Score: </label>
<output id='score'>0</output>
<br><br>
<p>Click <kbd>Start</kbd> button</p>
<p>Use the buttons ↑ ↓ → ← on your keyboard to move stop with the spacebar.</p>
add
var chrashed = 0;
and use
if (myGamePiece.crashWith(myObstacle)) {
crashed++;
showCrashed;
return startGame();
}
https://jsfiddle.net/mplungjan/m4w3ahj1/

I need to make the bricks randomly red or blue

Here's all the code (The variables are named properly so you should understand it)
The problem is that it resets all the bricks' colors randomly to red or blue but I want it to give a random color to each brick instead (70% of the time blue and 30% of the time red ).
var canvas, canvasContext;
var ballX = 75,
ballY = 75;
var ballSpeedX = 3,
ballSpeedY = 3;
var ballR = 7;
const brickW = 80;
const brickH = 20;
const brickCols = Math.floor(800 / brickW);
const brickRows = Math.floor(600 / (brickH * 3));
const brickGap = 1;
var brickGrid = new Array(brickCols * brickRows);
var bricksLeft = 0;
const paddleW = 100,
paddleH = 10;
var paddleX = 400,
paddleY = 600;
const distanceBP = 60;
var mouseX, mouseY;
function updateMousePos(evt) {
var rect = canvas.getBoundingClientRect(); // this is for adjustments only (getting the mouse coordinates even if the page is scrollable)
var root = document.documentElement;
mouseX = evt.clientX - rect.left - root.scrollLeft; // clientX is the X of mouse
mouseY = evt.clientY - rect.top - root.scrollTop;
paddleX = mouseX - paddleW / 2;
//cheat
//ballX = mouseX;
//ballY = mouseY;
}
function brickReset() {
bricksLeft = 0;
var i;
for (i = 0; i < 3 * brickCols; i++) {
brickGrid[i] = false;
}
for (; i < brickCols * brickRows; i++) {
brickGrid[i] = true;
bricksLeft++;
randBrickColor();
}
}
window.onload = function() {
canvas = document.getElementById("myCanvas");
canvasContext = canvas.getContext("2d");
var fps = 60;
setInterval(updateAll, 1000 / fps);
canvas.addEventListener("mousemove", updateMousePos); // everytime the mouse moves we call the function updateMousePos()
brickReset();
ballReset();
}
function updateAll() {
drawAll();
moveAll();
console.log(brickColor);
}
function ballReset() {
ballX = canvas.width / 2;
ballY = canvas.height / 2;
}
function ballMove() {
ballX += ballSpeedX;
ballY += ballSpeedY;
//COLLISION
//left
if (ballX - ballR < 0 && ballSpeedX < 0.0) {
ballSpeedX = -ballSpeedX;
}
//right
if (ballX + ballR > canvas.width && ballSpeedX > 0.0) {
ballSpeedX = -ballSpeedX;
}
//top
if (ballY - ballR < 0 && ballSpeedY < 0.0) {
ballSpeedY = -ballSpeedY;
}
//bottom
if (ballY > canvas.height) {
ballReset();
brickReset();
}
}
function isBrickAtColRow(col, row) {
if (col >= 0 && col < brickCols &&
row >= 0 && row < brickRows) {
var brickIndexUnderCoord = rowColToArrayIndex(col, row);
return brickGrid[brickIndexUnderCoord];
} else {
return false;
}
}
function ballBrickHandling() {
var ballBrickCol = Math.floor(ballX / brickW);
var ballBrickRow = Math.floor(ballY / brickH);
var brickIndexUnderBall = rowColToArrayIndex(ballBrickCol, ballBrickRow);
if (brickIndexUnderBall >= 0 &&
brickIndexUnderBall < brickCols * brickRows) {
if (isBrickAtColRow(ballBrickCol, ballBrickRow)) {
brickGrid[brickIndexUnderBall] = false;
bricksLeft--;
//console.log( bricksLeft)
var prevBallX = ballX - ballSpeedX;
var prevBallY = ballY - ballSpeedY;
var prevBrickCol = Math.floor(prevBallX / brickW);
var prevBrickRow = Math.floor(prevBallY / brickH);
var bothTestsFailed = true;
if (prevBrickCol != ballBrickCol) {
if (isBrickAtColRow(prevBrickCol, ballBrickRow) == false) {
ballSpeedX = -ballSpeedX;
bothTestsFailed = false;
}
}
if (prevBrickRow != ballBrickRow) {
if (isBrickAtColRow(ballBrickCol, prevBrickRow) == false) {
ballSpeedY = -ballSpeedY;
bothTestsFailed = false;
}
}
if (bothTestsFailed) {
ballSpeedX = -ballSpeedX;
ballSpeedY = -ballSpeedY;
}
}
}
}
function ballPaddleHandling() {
var paddleTopEdgeY = canvas.height - distanceBP;
var paddleBottomEdgeY = paddleTopEdgeY + paddleH;
var paddleLeftEdgeX = paddleX;
var paddleRightEdgeX = paddleLeftEdgeX + paddleW;
if (ballY + ballR > paddleTopEdgeY &&
ballY - ballR < paddleBottomEdgeY &&
ballX + ballR > paddleLeftEdgeX &&
ballX - ballR < paddleRightEdgeX) {
ballSpeedY *= -1;
var centerOfPaddleX = paddleX + paddleW / 2;
var ballDistFromPadlleCenterX = ballX - centerOfPaddleX;
ballSpeedX = ballDistFromPadlleCenterX * 0.2;
if (bricksLeft == 0) {
brickReset();
}
}
}
function moveAll() {
//console.log("X: "+ballSpeedX,"Y: "+ballSpeedY);
ballMove();
ballBrickHandling();
ballPaddleHandling();
}
function rowColToArrayIndex(col, row) {
return col + brickCols * row;
}
// Random COLOR
var brickColor = "blue";
function randBrickColor() {
if (Math.random() > 0.7) {
brickColor = "red";
} else brickColor = "blue";
return brickColor;
}
//end of Random COLOR
function drawBricks() {
for (var eachRow = 0; eachRow < brickRows; eachRow++) {
for (var eachCol = 0; eachCol < brickCols; eachCol++) {
var arrayIndex = brickCols * eachRow + eachCol;
if (brickGrid[arrayIndex]) {
colorRect(brickW * eachCol, brickH * eachRow, brickW - brickGap, brickH - brickGap, brickColor);
}
}
}
}
function drawAll() {
// Black Screen
colorRect(0, 0, canvas.width, canvas.height, "black");
// Ball
colorCircle(ballX, ballY, ballR, "white");
// Paddle
colorRect(paddleX, paddleY - distanceBP, paddleW, paddleH, "white");
// Bricks
drawBricks();
colorText(mouseX + "," + mouseY, mouseX, mouseY, "yellow");
}
function colorRect(topLeftX, topLeftY, boxWidth, boxHeight, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.fillRect(topLeftX, topLeftY, boxWidth, boxHeight);
}
function colorCircle(centerX, centerY, radius, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
canvasContext.fill();
}
function colorText(showWords, textX, textY, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.fillText(showWords, textX, textY);
}
<canvas id="myCanvas" width="800" height="600"></canvas>
You set the color once per brick but you overwrite the global variable before you do any drawing. So when it gets to drawBricks the loop that sets the brick colors has already finished and the variable stays the same throughout the drawing.
Since you repaint the bricks continuously (I'm not sure if it is necessary) I suggest you save a bidimensional array of randomized colors in you randBrickColor function instead of just a variable.
A summary of the changes:
Put the randBrickColor(); call outside the loop in brickReset().
Initialize a variable brickColors (instead of brickColor) as an array. Ex: var brickColors = [];
Change the function randBrickColor so it loops through brickRowsand brickCols and stores the randomized color under brickColors[eachRow][eachCol].
Use brickColors[eachRow][eachCol] in your drawBricks function to pick the color of each brick.
See the snippet below.
var canvas, canvasContext;
var ballX = 75,
ballY = 75;
var ballSpeedX = 3,
ballSpeedY = 3;
var ballR = 7;
const brickW = 80;
const brickH = 20;
const brickCols = Math.floor(800 / brickW);
const brickRows = Math.floor(600 / (brickH * 3));
const brickGap = 1;
var brickGrid = new Array(brickCols * brickRows);
var bricksLeft = 0;
const paddleW = 100,
paddleH = 10;
var paddleX = 400,
paddleY = 600;
const distanceBP = 60;
var mouseX, mouseY;
function updateMousePos(evt) {
var rect = canvas.getBoundingClientRect(); // this is for adjustments only (getting the mouse coordinates even if the page is scrollable)
var root = document.documentElement;
mouseX = evt.clientX - rect.left - root.scrollLeft; // clientX is the X of mouse
mouseY = evt.clientY - rect.top - root.scrollTop;
paddleX = mouseX - paddleW / 2;
//cheat
//ballX = mouseX;
//ballY = mouseY;
}
function brickReset() {
bricksLeft = 0;
var i;
for (i = 0; i < 3 * brickCols; i++) {
brickGrid[i] = false;
}
for (; i < brickCols * brickRows; i++) {
brickGrid[i] = true;
bricksLeft++;
}
randBrickColor();
}
window.onload = function() {
canvas = document.getElementById("myCanvas");
canvasContext = canvas.getContext("2d");
var fps = 60;
setInterval(updateAll, 1000 / fps);
canvas.addEventListener("mousemove", updateMousePos); // everytime the mouse moves we call the function updateMousePos()
brickReset();
ballReset();
}
function updateAll() {
drawAll();
moveAll();
}
function ballReset() {
ballX = canvas.width / 2;
ballY = canvas.height / 2;
}
function ballMove() {
ballX += ballSpeedX;
ballY += ballSpeedY;
//COLLISION
//left
if (ballX - ballR < 0 && ballSpeedX < 0.0) {
ballSpeedX = -ballSpeedX;
}
//right
if (ballX + ballR > canvas.width && ballSpeedX > 0.0) {
ballSpeedX = -ballSpeedX;
}
//top
if (ballY - ballR < 0 && ballSpeedY < 0.0) {
ballSpeedY = -ballSpeedY;
}
//bottom
if (ballY > canvas.height) {
ballReset();
brickReset();
}
}
function isBrickAtColRow(col, row) {
if (col >= 0 && col < brickCols &&
row >= 0 && row < brickRows) {
var brickIndexUnderCoord = rowColToArrayIndex(col, row);
return brickGrid[brickIndexUnderCoord];
} else {
return false;
}
}
function ballBrickHandling() {
var ballBrickCol = Math.floor(ballX / brickW);
var ballBrickRow = Math.floor(ballY / brickH);
var brickIndexUnderBall = rowColToArrayIndex(ballBrickCol, ballBrickRow);
if (brickIndexUnderBall >= 0 &&
brickIndexUnderBall < brickCols * brickRows) {
if (isBrickAtColRow(ballBrickCol, ballBrickRow)) {
brickGrid[brickIndexUnderBall] = false;
bricksLeft--;
//console.log( bricksLeft)
var prevBallX = ballX - ballSpeedX;
var prevBallY = ballY - ballSpeedY;
var prevBrickCol = Math.floor(prevBallX / brickW);
var prevBrickRow = Math.floor(prevBallY / brickH);
var bothTestsFailed = true;
if (prevBrickCol != ballBrickCol) {
if (isBrickAtColRow(prevBrickCol, ballBrickRow) == false) {
ballSpeedX = -ballSpeedX;
bothTestsFailed = false;
}
}
if (prevBrickRow != ballBrickRow) {
if (isBrickAtColRow(ballBrickCol, prevBrickRow) == false) {
ballSpeedY = -ballSpeedY;
bothTestsFailed = false;
}
}
if (bothTestsFailed) {
ballSpeedX = -ballSpeedX;
ballSpeedY = -ballSpeedY;
}
}
}
}
function ballPaddleHandling() {
var paddleTopEdgeY = canvas.height - distanceBP;
var paddleBottomEdgeY = paddleTopEdgeY + paddleH;
var paddleLeftEdgeX = paddleX;
var paddleRightEdgeX = paddleLeftEdgeX + paddleW;
if (ballY + ballR > paddleTopEdgeY &&
ballY - ballR < paddleBottomEdgeY &&
ballX + ballR > paddleLeftEdgeX &&
ballX - ballR < paddleRightEdgeX) {
ballSpeedY *= -1;
var centerOfPaddleX = paddleX + paddleW / 2;
var ballDistFromPadlleCenterX = ballX - centerOfPaddleX;
ballSpeedX = ballDistFromPadlleCenterX * 0.2;
if (bricksLeft == 0) {
brickReset();
}
}
}
function moveAll() {
//console.log("X: "+ballSpeedX,"Y: "+ballSpeedY);
ballMove();
ballBrickHandling();
ballPaddleHandling();
}
function rowColToArrayIndex(col, row) {
return col + brickCols * row;
}
// Random COLOR
var brickColors = [];
function randBrickColor() {
for (var eachRow = 0; eachRow < brickRows; eachRow++) {
brickColors[eachRow] = [];
for (var eachCol = 0; eachCol < brickCols; eachCol++) {
if (Math.random() > 0.7) {
brickColors[eachRow][eachCol] = "red";
} else brickColors[eachRow][eachCol] = "blue";
}
}
}
//end of Random COLOR
function drawBricks() {
for (var eachRow = 0; eachRow < brickRows; eachRow++) {
for (var eachCol = 0; eachCol < brickCols; eachCol++) {
var arrayIndex = brickCols * eachRow + eachCol;
if (brickGrid[arrayIndex]) {
colorRect(brickW * eachCol, brickH * eachRow, brickW - brickGap, brickH - brickGap, brickColors[eachRow][eachCol]);
}
}
}
}
function drawAll() {
// Black Screen
colorRect(0, 0, canvas.width, canvas.height, "black");
// Ball
colorCircle(ballX, ballY, ballR, "white");
// Paddle
colorRect(paddleX, paddleY - distanceBP, paddleW, paddleH, "white");
// Bricks
drawBricks();
colorText(mouseX + "," + mouseY, mouseX, mouseY, "yellow");
}
function colorRect(topLeftX, topLeftY, boxWidth, boxHeight, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.fillRect(topLeftX, topLeftY, boxWidth, boxHeight);
}
function colorCircle(centerX, centerY, radius, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
canvasContext.fill();
}
function colorText(showWords, textX, textY, fillColor) {
canvasContext.fillStyle = fillColor;
canvasContext.fillText(showWords, textX, textY);
}
<canvas id="myCanvas" width="800" height="600"></canvas>

JS Galaxian Shooter enemies shooting

Hey i'm trying to make a super simple Galaxian Shooter game. I'm having a problem in making all the enemies in the enemy list shoot separately. Right now, only one shoots bullets. I know there are a lot of better ways to do things in this code, I just haven't made it efficient yet and I'm fixing it all so please don't say anything about that. Lines 193,86,72, and 42 all have something do with the enemyBulletList, if that helps.
var c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
keys = [];
width = 500;
height = 500;
bulletList = {};
enemyBulletList = {};
enemyList = {};
enemyAmount = 10;
var player = {
x:400,
y:450,
speedX:7,
speedY:7,
width:32,
height:32,
hp:3,
shootCdTimer:0,
shootCd:1,
};
tickShootCooldown = function(){
player.shootCdTimer--;
}
setInterval(tickShootCooldown,500);
onGameStart = function(){
generateEnemy();
generateBullet();
generateEnemyBullet();
setInterval(changeEnemyDirection,2000);
setInterval(changeEnemyDirection2,4000);
}
setTimeout(onGameStart,0);
Bullet = function(id,x,y,speedX,speedY,width,height) {
var asd = {
x:x,
y:y,
speedX:speedX,
speedY:speedY,
name:'B',
id:id,
width:width,
height:height,
color:'black',
};
bulletList[id] = asd;
}
generateBullet = function() {
var x = player.x;
var y = player.y;
var width = 5;
var height = 15;
var id = Math.random();
var speedX = 0;
var speedY = 15;
Bullet(id,x,y,speedX,speedY,width,height);
}
EnemyBullet = function(id,x,y,speedX,speedY,width,height) {
var asd = {
x:x,
y:y,
speedX:speedX,
speedY:speedY,
name:'B',
id:id,
width:width,
height:height,
color:'black',
};
enemyBulletList[id] = asd;
}
generateEnemyBullet = function() {
for(var key3 in enemyList){
var x = enemyList[key3].x;
var y = enemyList[key3].y;
}
var width = 5;
var height = 15;
var id = Math.random();
var speedX = 0;
var speedY = -15;
EnemyBullet(id,x,y,speedX,speedY,width,height);
}
Enemy = function(id,x,y,speedX,speedY,width,height) {
var asd = {
x:x,
y:y,
speedX:speedX,
speedY:speedY,
name:'B',
id:id,
width:width,
height:height,
color:'red',
};
enemyList[id] = asd;
}
generateEnemy = function() {
var x = 50;
var y = 50;
var width = 32;
var height = 32;
var id = 1;
var speedX = 2;
var speedY = 0;
Enemy(id,x,y,speedX,speedY,width,height);
Enemy(id*2,x*2,y,speedX,speedY,width,height);
Enemy(id*3,x*3,y,speedX,speedY,width,height);
Enemy(id*4,x*4,y,speedX,speedY,width,height);
Enemy(id*5,x*5,y,speedX,speedY,width,height);
Enemy(id*6,x,y*2,speedX,speedY,width,height);
Enemy(id*7,x*2,y*2,speedX,speedY,width,height);
Enemy(id*8,x*3,y*2,speedX,speedY,width,height);
Enemy(id*9,x*4,y*2,speedX,speedY,width,height);
Enemy(id*10,x*5,y*2,speedX,speedY,width,height);
}
changeEnemyDirection = function() {
for(var key in enemyList){
if(enemyList[key].speedX > 0){
enemyList[key].speedX *= -1;
}
}
}
changeEnemyDirection2 = function() {
for(var key in enemyList){
if(enemyList[key].speedX < 0){
enemyList[key].speedX *= -1;
}
}
}
function update() {
ctx.clearRect(0, 0, width, height);
ctx.fillRect(player.x,player.y,player.width,player.height);
if(enemyAmount < 1){
generateEnemy();
enemyAmount = 10;
}
if(player.x < player.width/2){
player.x = player.width/2;
}
if(player.x > width - player.width){
player.x = width - player.width;
}
if(player.y < height-150){
player.y = height-150;
}
if(player.y > height-32){
player.y = height-33;
}
if (keys[39]) { //right arrow
player.x+=player.speedX;
}
if (keys[37]) { //left arrow
player.x-=player.speedX;
}
if (keys[38]) { //up arrow
player.y-=player.speedY;
}
if (keys[40]) { //down arrow
player.y+=player.speedY;
}
if (keys[32]) { //space bar
if(player.shootCdTimer<=0){
generateBullet();
player.shootCdTimer = player.shootCd;
}
}
for(var key in bulletList) {
updateEntity(bulletList[key]);
}
for(var keyy in enemyBulletList) {
updateEntity(enemyBulletList[keyy]);
}
for(var key2 in enemyList) {
var isColliding = testCollisionEntity(bulletList[key],enemyList[key2]);
if(isColliding) {
delete enemyList[key2];
enemyAmount --;
delete bulletList[key];
break;
}
}
//for(var key3 in enemyList){
var timer = Math.random();
if(timer <= 0.01){
generateEnemyBullet(enemyList[key2]);
}
// }
for(var key in enemyList){ //change to collision with enemy bullet
updateEntity(enemyList[key]);
var isColliding = testCollisionEntity(player,enemyList[key]);
if(isColliding){
player.hp = player.hp - 1;
}
}
ctx.fillText(player.shootCdTimer,5,10);
}
setInterval(update,20);
testCollisionEntity = function (entity1,entity2){ //return if colliding (true/false)
var rect1 = {
x:entity1.x-entity1.width/2,
y:entity1.y-entity1.height/2,
width:entity1.width,
height:entity1.height,
}
var rect2 = {
x:entity2.x-entity2.width/2,
y:entity2.y-entity2.height/2,
width:entity2.width,
height:entity2.height,
}
return testCollisionRectRect(rect1,rect2);
}
testCollisionRectRect = function(rect1,rect2){
return rect1.x <= rect2.x+rect2.width
&& rect2.x <= rect1.x+rect1.width
&& rect1.y <= rect2.y + rect2.height
&& rect2.y <= rect1.y + rect1.height;
}
updateEntity = function(something){
updateEntityPosition(something);
drawEntity(something);
}
updateEntityPosition = function(something){
something.x += something.speedX;
something.y -= something.speedY;
}
drawEntity = function(something){
ctx.save();
ctx.fillStyle = something.color;
ctx.fillRect(something.x-something.width/2,something.y-something.height/2,something.width,something.height);
ctx.restore();
}
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">

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