Jump to content

  • Log In with Google      Sign In   
  • Create Account

appendChild() and removeChild() problems in JS


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 Patriarch K   Members   -  Reputation: 212

Like
0Likes
Like

Posted 20 March 2013 - 07:20 AM

I have a menu and from the meny I append a child called game.js which will start the game. When I complete the first stage, I want to remove the child game.js and append game2.js, but that doesn't work for me. How shall I solve this? I will show you the menu code only, where I append the child and that works fine. But later on, when I am in the game.js and press a key just for testing, then I want the current child (game.js) to be removed and I want to start the game2.js at the same time so that there will be a level change when I press a button from level 1.

 


var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');


var pendingImages = 1;
var menuStart = false;
var newScript = window.document.createElement("script");

var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        window.oRequestAnimationFrame;

var music = new Audio("images/rymd2.ogg");
music.loop = true;
music.play();

var startmeny = new Image();
startmeny.src = 'images/startmeny.png';
startmeny.addEventListener('load', imageLoaded, false);

// main functions
function init() {
    loop();
    document.addEventListener('keydown', checkKeyDown, false);
}

function loop() {  
     if(menuStart == false){
     updateGame();  
     requestAnimFrame(loop);  
     }  
}

function imageLoaded()
{
    --pendingImages;
    if (pendingImages == 0)
    {
        init();
    }
}

function updateGame(){
  ctxBg.drawImage(startmeny, 0, 0); 
}

function clearCtxBg() {
    ctxBg.clearRect(0, 0, 800, 600);
}
// end of main functions

// event functions
function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 13 ) { //enter
          e.preventDefault();
          newScript.src = "game.js";
          window.document.body.appendChild(newScript); 
          music.pause();
          menuStart = true;
    }

}
// end of event functions

 

 



Sponsor:

#2 HappyCoder   Members   -  Reputation: 2664

Like
3Likes
Like

Posted 20 March 2013 - 10:49 AM

I would have to confirm this but I would think that even after removing the script tag the code in it would still be defined and would continue to run. Also, trying to rely on loading and unloading a source file to control behavior sounds a little shaky to me. I would search for a way to load all of your source at the beginning then have another way to control what code is active.

I am assuming you are using the same names for functions in the different source files, so loading both at the same time would cause conflicts. If that is so the following might work well for you.

game.js
// create the game one object
var GameOne = {}

// add all the functions for game one into 
// the GameOne object
GameOne.updateGame = function(){
  ctxBg.drawImage(startmeny, 0, 0); 
}

// then add these
GameOne.becomeActive = function() {
   // add event listeners, or do other game setup
}

GameOne.resignActive = function() {
   // remove event listeners, do any cleanup
}

game2.js
// do the same thing for game two, only with whatever logic you want there
var GameTwo = {}
GameTwo.updateGame = function(){
   // game logic
}
GameTwo.becomeActive = function() {
   // add event listeners, or do other game setup
}

GameTwo.resignActive = function() {
   // remove event listeners, do any cleanup
}
Now each game is defined in a separate object so in your main game loop code you could have something like this
var activeScene = null;

function setActiveScene(game)
{
    // tell the active game it is going away
    if (activeScene)
        activeScene.resignActive();

    activeScene = game;

    // alert the active game it is now active
    if (game)
        game.becomeActive();
}

// set the starting scene
setActiveScene(GameOne);

function loop() {
     // update the active game
     activeScene.updateGame();  
     requestAnimFrame(loop);
}

I would give more meaningful names to your GameOne and GameTwo object. I just used those names for this example. Perhaps something like MainMenu, Level1, ect... Then whenever you want to change to another scene you simply call setActiveScene(Level1)

Edited by HappyCoder, 20 March 2013 - 10:50 AM.


#3 Patriarch K   Members   -  Reputation: 212

Like
0Likes
Like

Posted 20 March 2013 - 01:49 PM

Hmm, that sound kind of complicated. I don't really get how to do even though I get the idea. It actually works well using booleans on the becomeActive/resignActive (like the animator and the key inputs), but there are a lot of variable collisions I've seen so maybe if I just rename all of the variables from the previous level to something else? Hmm, that's kind of ugly coding though.

Isn't there an easier way doing this?! smile.png

 

Could it be an idea putting all of the variables in a separate document and then use other .js modifying them?

Or can I somehow make the variables from one document NOT to be reachable by another .js?


Edited by Patriarch K, 20 March 2013 - 01:57 PM.


#4 Barzai   GDNet+   -  Reputation: 641

Like
1Likes
Like

Posted 20 March 2013 - 09:55 PM

Wow, it's certainly an interesting idea.  I generally make a distinct game object, then use a variable that tells my other code which game object to use, similar to HappyCoder's suggestion, I think.

 

Out of curiosity, when you attempt the change from js1 to js2, exactly how are you doing it?  And, it may be overly simple, but have you tried just changing the newScript.src parameter to game2.js instead of adding and removing children?  Doing that may need some sort of document reload command, though, if it would work at all.

 

If you make this approach with the DOM work, please post your solution.  It would be interesting to see how you went about it.



#5 Patriarch K   Members   -  Reputation: 212

Like
0Likes
Like

Posted 21 March 2013 - 04:15 AM

Well, my way of changing the level would be as you can see here in my "game.js". You can just search for .js and you will find it. Even if it would work by changing the child as I try to do, I would gladly like to do like you guys adviced. How can I rewrite my code in the way you and HappyCoder mentioned? Now you have all my code. The main and the game1. The game2 is just a copy of game one. Just ignore all the code, I just need some kind of general clue of how to change this.

 


var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');

var jet1 = new Jet();
var boss1 = new Boss();
var word1 = new Word();
var word2 = new Word2();
var word3 = new Word3();
var star1x = 0;
var star1y = 0;
var star1dx = -2.4;
var star1dy = 0;
var star2x = 0;
var star2y = 0;
var star2dx = -1.4;
var star2dy = 0;
var star3x = 0;
var star3y = 0;
var star3dx = -.4;
var star3dy = 0;
var kills = 0;
var pause = false;
var pauseCounter = 0;
//var bossLife = 40;
var timerOn = true;
var countdown = 15000;
var earthX = 800;
var earthY = 200;
var pendingImages = 22;
var difficulty = 100;
var shootCounter = 0;
var shootLimit = 34;
var finishedGame = false;
var earthDead = false;
var gameStart = true;

var newScript = window.document.createElement("script");
var endPress = false;
var weaponSpeed = 0;
var w1tim = 0;
var ran1 = Math.floor((Math.random()*7500)+500);
var ran2 = Math.floor((Math.random()*7500)+800);
var ran3 = Math.floor((Math.random()*7500)+1000);


var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        window.oRequestAnimationFrame;
var klaver = new Audio("images/klaver.mp3");
var hit = new Audio("images/hit.mp3");
var shoot = new Audio("images/laser.mp3");
var music = new Audio("images/rymd2.ogg");
var die = new Audio("images/die.ogg");
music.loop = true;
music.play();

var background = new Image();
background.src = 'images/background.png';
background.addEventListener('load', imageLoaded, false);

var bullet = new Image();
bullet.src = 'images/Bullet.gif';
bullet.addEventListener('load', imageLoaded, false);

var star1 = new Image();
star1.src = 'images/background3c.png';
star1.addEventListener('load', imageLoaded, false);

var star2 = new Image();
star2.src = 'images/background3b.png';
star2.addEventListener('load', imageLoaded, false);

var star3 = new Image();
star3.src = 'images/background3a.png';
star3.addEventListener('load', imageLoaded, false);

var star1b = new Image();
star1b.src = 'images/background4c.png';
star1b.addEventListener('load', imageLoaded, false);

var star2b = new Image();
star2b.src = 'images/background4b.png';
star2b.addEventListener('load', imageLoaded, false);

var star3b = new Image();
star3b.src = 'images/background4a.png';
star3b.addEventListener('load', imageLoaded, false);

var enemySprite = new Image();
enemySprite.src = 'images/enemySprite.png';
enemySprite.addEventListener('load', imageLoaded, false);

var boss = new Image();
boss.src = 'images/bossSprite.png';
boss.addEventListener('load', imageLoaded, false);

var sprite = new Image();
sprite.src = 'images/planeSprite.png';
sprite.addEventListener('load', imageLoaded, false);

var startmeny = new Image();
startmeny.src = 'images/startmeny.png';
startmeny.addEventListener('load', imageLoaded, false);

var earth = new Image();
earth.src = 'images/earth.png';
earth.addEventListener('load', imageLoaded, false);

var ed = new Image();
ed.src = 'images/earthdead.png';
ed.addEventListener('load', imageLoaded, false);

var finish = new Image();
finish.src = 'images/finish.png';
finish.addEventListener('load', imageLoaded, false);

var fail = new Image();
fail.src = 'images/fail.png';
fail.addEventListener('load', imageLoaded, false);

var w1 = new Image();
w1.src = 'images/f.gif';
w1.addEventListener('load', imageLoaded, false);

var w2 = new Image();
w2.src = 'images/i.gif';
w2.addEventListener('load', imageLoaded, false);

var w3 = new Image();
w3.src = 'images/r.gif';
w3.addEventListener('load', imageLoaded, false);

var b1 = new Image();
b1.src = 'images/missile.gif';
b1.addEventListener('load', imageLoaded, false);

var b2 = new Image();
b2.src = 'images/spike.gif';
b2.addEventListener('load', imageLoaded, false);

var b3 = new Image();
b3.src = 'images/speed.gif';
b3.addEventListener('load', imageLoaded, false);


// main functions
function init() {
    
    loop();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
}

function loop() { 
    if(pause == false){
     updateGame();  
   }
   if(timerOn == true){
       requestAnimFrame(loop); 
     }
}

function imageLoaded()
{
    --pendingImages;
    if (pendingImages == 0)
    {
        init();
    }
}

var spriteX = 0;
var spriteY = 0;
var enemySpriteX = 0;
var bossSpriteX = 0;
var spriteXstor = 100;
var spriteYstor = 55;
var enemySpriteXstor = 50;
var enemySpriteYstor = 50;
var bossSpriteXstor = 100;
var bossSpriteYstor = 100;
var changer = 1;
var lol = false;
var timerAnim = 0;
var bossDead = false;

function redrawTest() {
  if(jet1.direction == 1){
     ctxBg.drawImage(sprite, spriteX, 0, spriteXstor, spriteYstor, jet1.drawX, jet1.drawY, spriteXstor, spriteYstor);
 }
  else if(jet1.direction == -1){
     ctxBg.drawImage(sprite, spriteX, 55, spriteXstor, spriteYstor, jet1.drawX, jet1.drawY, spriteXstor, spriteYstor);
 }
}





function updateSprite(){
    redrawTest();
if(lol == false){
spriteX += 100;
enemySpriteX += 50;
bossSpriteX += 100;
if(spriteX >= 500 ){
    spriteX = 0;
}
if(enemySpriteX >= 150 ){
    enemySpriteX = 0;
}
if(bossSpriteX >= 700 ){
    bossSpriteX = 0;
}
lol = true;
} 
}

function updateGame(){
if(gameStart == false){
  ctxBg.drawImage(startmeny, 0, 0);
}
 
if(gameStart == true){
 ctxBg.drawImage(background, 0, 0);

     timerAnim++;
     shootCounter++;
     w1tim++;
     if(timerAnim == 5){
lol = false;
        timerAnim = 0;
     }  
      
if(countdown > 0){
countdown--;
}

if(countdown <= 5000){
if(earthDead == false){
    ctxBg.drawImage(earth, earthX, earthY);
  }
    if(earthDead == true){
      ctxBg.drawImage(ed, earthX, earthY);
    }
    if(countdown > 0){
    earthX -= 0.1;
}
}
        jet1.draw();
       
       if(finishedGame == false && bossDead == false){
        jet1.spawnEnemy();
        jet1.collision();
      }
        
        drawStars();
        redrawTest();
        diffSet();
        if(countdown > 0){
         jet1.move();
        moveStar1();
        moveStar2();
        moveStar3();
       
        boss1.moveBoss();
        boss1.draw();
        boss1.collision();
       if(w1tim >= 1000+ran1){
        word1.draw();
        word1.moveWord();
        word1.collision();
      }
        if(w1tim >= 1000+ran2){
        word2.draw();
        word2.moveWord();
        word2.collision();
      }
        if(w1tim >= 1000+ran3){
        word3.draw();
        word3.moveWord();
        word3.collision();
      }
        
updateSprite();
        if(countdown <= 1 && finishedGame == false){
            earthDead = true;
            finishedGame = true;
         
        }
         else if(earthDead == true){
 ctxBg.drawImage(fail, 0, 0);
         }

        else if(boss1.bossLife <= 0 && finishedGame == false){
           
            die.play();
            bossDead = true;
            finishedGame = true;

        }
        else if(finishedGame == true){
           ctxBg.drawImage(finish, 0, 0);
endPress = true;
        }
    }
     drawText();
       
}
   
}

function diffSet(){
   
if(jet1.weapon == 0){
  weaponSpeed = 0; // standard
}
else if(jet1.weapon == 1){
  weaponSpeed = 10; //missile
}
else if(jet1.weapon == 2){
  weaponSpeed = 20; // rock
}
else if(jet1.weapon == 3){
  weaponSpeed = -20; // speed
}



    if(kills < 5){
    difficulty = 100;
    shootLimit = 34+weaponSpeed;
    }
    else if(kills >= 5 && kills < 10){
    difficulty = 95;
    shootLimit = 30+weaponSpeed;
    }
    else if(kills >= 10 && kills < 20){
    difficulty = 90;  
    shootLimit = 25+weaponSpeed;  
    }
    else if(kills >= 20 && kills < 30){
     difficulty = 80; 
     shootLimit = 23+weaponSpeed;  
    }
    else if(kills >= 30 && kills < 40){
     difficulty = 65;  
     shootLimit = 21+weaponSpeed; 
    }
    else if(kills >= 40 && kills < 50){
     difficulty = 55; 
     shootLimit = 19+weaponSpeed;  
    }
    else if(kills >= 50 && kills < 60){
      difficulty = 40; 
      shootLimit = 17+weaponSpeed; 
    }
    else if(kills >= 60 && kills < 70){
      difficulty = 30; 
      shootLimit = 12+weaponSpeed; 
    }
    else if(kills >= 70 && kills < 80){
       difficulty = 20; 
       shootLimit = 7+weaponSpeed;
    }
    else if(kills >= 80 && kills < 90){
      difficulty = 10; 
      shootLimit = 3+weaponSpeed; 
    }
    else if(kills >= 90 && kills < 100){
      difficulty = 8;  
      shootLimit = 1+weaponSpeed;
    }
}


function drawStars(){
    if(countdown > 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 
}
          else if(countdown <= 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1b, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1b, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1b, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2b, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2b, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2b, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3b, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3b, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3b, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 

}
 
}


function moveStar1(){
star1x += star1dx;
}

function moveStar2(){
star2x += star2dx;
}

function moveStar3(){
star3x += star3dx;
}




function drawText(){
ctxBg.lineWidth=1;
ctxBg.fillStyle="#FFFFFF";
ctxBg.lineStyle="#ffff00";
ctxBg.font="18px sans-serif";
ctxBg.fillText("Power: " + kills, 20, 20);
ctxBg.fillText(countdown + " km to Earth", 650, 20);
}


function clearCtxBg() {
    ctxBg.clearRect(0, 0, 800, 600);
}

// end of main functions
// jet functions
function Jet() {
   
    this.drawX = 100;
    this.drawY = 200;
    this.dx = 0;
    this.dy = 0;
    this.direction = 1;
    this.fire = false;
    this.isShooting = false;
    this.bullets = [];
    this.currentBullet = 0;
    this.counter = 0;
    this.enemyRand;
    this.enemyRand2;
    //this.bossLife = 40;
    this.collisiontest = false;

    this.weapon = 0;

    this.enemies = [];
    this.currentEnemy = 0;
    for (var y = 0; y < 800; y++) {
        this.bullets[this.bullets.length] = new Bullet();
    }
     for (var u = 0; u < 300; u++) {
        this.enemies[this.enemies.length] = new Enemy();
    }
}

Jet.prototype.move = function(){
    this.drawX += this.dx;
    this.drawY += this.dy;
}

Jet.prototype.draw = function() {
    clearCtxJet();
    this.fireBullet();
    this.drawAllBullets();
    this.drawAllEnemies();
   
}

Jet.prototype.drawAllBullets = function() {
    for (var ii = 0; ii < this.bullets.length; ii++) {
        if (this.bullets[ii].drawX >= 0 && this.bullets[ii].bulletLifea > 0) {
            this.bullets[ii].draw();
            this.bullets[ii].move();
           
        
       
        }
    }    
}

Jet.prototype.collision = function() {
   
 for (var i = 0; i < this.bullets.length; i++) {
   
 
    for (var j = 0; j < this.enemies.length; j++) {
        // Minuspoäng när fiender är utanför skärmen
            if(this.enemies[j].drawX > -10 && this.enemies[j].drawX < 0 && this.enemies[j].outScreen == false){
kills--;
this.enemies[j].outScreen = true;
klaver.play();
            }
// Om en bullet krockar med en fiende
            if(this.bullets[i].drawX > this.enemies[j].drawX && this.bullets[i].drawX < this.enemies[j].drawX+50 && this.bullets[i].drawY+30 > this.enemies[j].drawY && this.bullets[i].drawY < this.enemies[j].drawY+25 && this.bullets[i].bulletLifea > 0 && this.enemies[j].life > 0 ){
                if(jet1.weapon == 0){
                this.enemies[j].life-=2;
              }
              else if(jet1.weapon == 1){
                this.enemies[j].life-=6;
              }
              else if(jet1.weapon == 2){
                this.enemies[j].life-=3;
              }
              else if(jet1.weapon == 3){
                this.enemies[j].life--;
              }

                if(this.enemies[j].life < 1){
                    kills++;
                    hit.play();
                }
                 
                this.bullets[i].bulletLifea--;

                
            }
        }
      } 
}


Jet.prototype.drawAllEnemies = function() {
    for (var ij = 0; ij < this.enemies.length; ij++) {
        if (this.enemies[ij].drawX >= 0) {
           if(this.enemies[ij].life > 0){
            this.enemies[ij].draw();
            this.enemies[ij].move();
        }
        
       
        }
    }    
}

Jet.prototype.fireBullet = function() {
    if (this.fire == true && this.isShooting == false) {
        this.isShooting = true;
        if(this.bullets[this.currentBullet].bulletLifea > 0){
            if(this.direction == 1){
        this.bullets[this.currentBullet].fire(this.drawX+95, this.drawY);
    }
         if(this.direction == -1){
        this.bullets[this.currentBullet].fire(this.drawX, this.drawY);
    }

shoot.play();
        this.bullets[this.currentBullet].isShot = true;
    }
        if(this.direction == 1){
            this.bullets[this.currentBullet].dxa = 8;
        }
        if(this.direction == -1){
             this.bullets[this.currentBullet].dxa = -8;
        }
        this.currentBullet++;
       
        if (this.currentBullet >= this.bullets.length) this.currentBullet = 0;
        
    } else if (this.fire == false) {
        this.isShooting = false;
    }  
}

Jet.prototype.spawnEnemy = function(){
    this.counter++;
    this.enemyRand = Math.floor((Math.random()*500)+difficulty);
    this.enemyRand2 = Math.floor((Math.random()*550)+1);
     if (this.counter >= this.enemyRand) {
        
        this.enemies[this.currentEnemy].fire(800, this.enemyRand2);
        this.currentEnemy++;
       
        if (this.currentEnemy >= this.enemies.length) {
            this.currentEnemy = 0;
        }
        this.counter = 0;
    }   
}


function clearCtxJet() {
    ctxJet.clearRect(0, 0, 800, 600);
    ctxBullet.clearRect(0, 0, 800, 600);
}

// end of jet functions
// bullet functions
function Bullet() {
    this.drawX = -20;
    this.drawY = 0;
    this.dxa = 3;
    this.dya = 1;
    this.isShot = false;
    this.bulletLifea = 1;
    this.gravity = 10;
    this.dt = .2;

}

Bullet.prototype.move = function(){
if(jet1.weapon == 0){
this.drawX += this.dxa;
}
else if(jet1.weapon == 1){

//if(this.drawX + this.dx > 780){
    //  this.dx = -this.dx;
   // }
   // if(this.drawX + this.dx < 0){
    //  this.dx = -this.dx;
   // }
   // else{
    //  this.drawX += this.dx;  
   // }
   this.dxa = 0;
      this.dya += this.gravity * this.dt;
      this.drawY += this.dya*this.dt + .2*this.gravity*this.dt*this.dt;



}
else if(jet1.weapon == 2){
     
      this.drawX += this.dxa;  
      this.dya += this.gravity * this.dt;
      this.drawY += this.dya*this.dt + .2*this.gravity*this.dt*this.dt;
     

}
else if(jet1.weapon == 3){
  
this.drawX += this.dxa;

 

}
}

Bullet.prototype.draw = function() {
   if( this.bulletLifea > 0){
    if(jet1.weapon == 0){
    ctxBullet.drawImage(bullet, this.drawX, this.drawY+25);
  }
  else if(jet1.weapon == 1){
    ctxBullet.drawImage(b1, this.drawX, this.drawY+25);
  }
  else if(jet1.weapon == 2){
    ctxBullet.drawImage(b2, this.drawX, this.drawY+25);
  }
  else if(jet1.weapon == 3){
    ctxBullet.drawImage(b3, this.drawX, this.drawY+25);
  }
}
  
}

Bullet.prototype.fire = function(startX, startY) {
   
   
    this.drawX = startX;
    this.drawY = startY;
  
}

// end of bullet functions


// boss functions
function Boss() {
  
    this.bossX = 200;
this.bossY = 200;
this.bossDX = 3;
this.bossDY = 3;
this.bossLife = 20;

}



Boss.prototype.moveBoss = function(){
    this.bossX += this.bossDX;
    this.bossY += this.bossDY;

if(this.bossX <= 0 || this.bossX >= 750){
    this.bossDX *= -1;
}
if(this.bossY <= 0 || this.bossY >= 550){
    this.bossDY *= -1;
}

}


Boss.prototype.collision = function(){

   for (var i = 0; i < jet1.bullets.length; i++) {
   
  // Skjuta på bossen
    if(kills >= 50){    
if(jet1.bullets[i].drawX > this.bossX && jet1.bullets[i].drawX < this.bossX+100 && jet1.bullets[i].drawY > this.bossY && jet1.bullets[i].drawY < this.bossY+90 && jet1.bullets[i].bulletLifea > 0 && this.bossLife > 0){
    
   
   jet1.bullets[i].bulletLifea--;
   if(jet1.weapon == 0){
   this.bossLife-=2;
 }
 else if(jet1.weapon == 1){
   this.bossLife-=6;
 }
 else if(jet1.weapon == 2){
   this.bossLife-=3;
 }
 else if(jet1.weapon == 3){
   this.bossLife--;
 }
  
 }
}
}
}


Boss.prototype.draw = function() {
  if(kills >= 50 && this.bossLife > 0){
        
       ctxBg.drawImage(boss, bossSpriteX, 0, bossSpriteXstor, bossSpriteYstor, this.bossX, this.bossY, bossSpriteXstor, bossSpriteYstor);

     }
  
}



// end of boss functions

// word functions
function Word() { 
this.wordX = 800;
this.wordY = 200;
this.wordDX = -3;
this.wordDY = 3;
this.wordLife = 1;
}

Word.prototype.moveWord = function(){
    this.wordX += this.wordDX;
}

Word.prototype.collision = function(){
  if(jet1.drawX+80 >= this.wordX && jet1.drawY+25 >= this.wordY && jet1.drawY+25 <= this.wordY+20 && jet1.drawX <= this.wordX+15 ){
      this.wordLife--;
      jet1.weapon = 1;
  } 
}

Word.prototype.draw = function() {
     if(this.wordLife > 0){
       ctxBg.drawImage(w1, this.wordX, this.wordY);
     }
}
// end of word functions
// word2 functions
function Word2() { 
this.wordX = 800;
this.wordY = 100;
this.wordDX = -3;
this.wordDY = 3;
this.wordLife = 1;
}

Word2.prototype.moveWord = function(){
    this.wordX += this.wordDX;
}

Word2.prototype.collision = function(){
  if(jet1.drawX+80 >= this.wordX && jet1.drawY+25 >= this.wordY && jet1.drawY+25 <= this.wordY+20 && jet1.drawX <= this.wordX+15 ){
      this.wordLife--;
      jet1.weapon = 2;
  } 
}

Word2.prototype.draw = function() {
     if(this.wordLife > 0){
       ctxBg.drawImage(w2, this.wordX, this.wordY);
     }
}
// end of word2 functions
// word3 functions
function Word3() { 
this.wordX = 800;
this.wordY = 300;
this.wordDX = -3;
this.wordDY = 3;
this.wordLife = 1;
}

Word3.prototype.moveWord = function(){
    this.wordX += this.wordDX;
}

Word3.prototype.collision = function(){
  if(jet1.drawX+80 >= this.wordX && jet1.drawY+25 >= this.wordY && jet1.drawY+25 <= this.wordY+20 && jet1.drawX <= this.wordX+15 ){
      this.wordLife--;
      jet1.weapon = 3;
  } 
}

Word3.prototype.draw = function() {
     if(this.wordLife > 0){
       ctxBg.drawImage(w3, this.wordX, this.wordY);
     }
}
// end of word3 functions




// enemy functions
function Enemy() {
    this.drawX = -20;
    this.drawY = 0;
    this.dx;
    this.isShot = false;
    this.life = 6;
    this.outScreen = false;
}

Enemy.prototype.move = function(){
if(this.life == 6){
this.dx = 2.5;
}
if(this.life == 4){
this.dx = 4.1;
}
if(this.life == 2){
this.dx = 6;
}
this.drawX -= this.dx;
}

Enemy.prototype.draw = function() {
   
   if(this.life > 4){
     ctxBullet.drawImage(enemySprite, enemySpriteX, 0, enemySpriteXstor, enemySpriteYstor, this.drawX, this.drawY, enemySpriteXstor, enemySpriteYstor);
  
}
  if(this.life > 2 && this.life <= 4){
    ctxBullet.drawImage(enemySprite, enemySpriteX, 50, enemySpriteXstor, enemySpriteYstor, this.drawX, this.drawY, enemySpriteXstor, enemySpriteYstor);

   
}
  if(this.life > 0 && this.life <= 2){
         ctxBullet.drawImage(enemySprite, enemySpriteX, 100, enemySpriteXstor, enemySpriteYstor, this.drawX, this.drawY, enemySpriteXstor, enemySpriteYstor);

  
}


}

Enemy.prototype.fire = function(startX, startY) {
    this.drawX = startX;
    this.drawY = startY;
}

// end of enemy functions





// event functions

function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
   if(timerOn == true){
    if (keyID === 38 ) { //up arrow
         e.preventDefault();
         jet1.dy = -3;    
    }
    if (keyID === 39 ) { //right arrow
      jet1.direction = 1;
         e.preventDefault();
        jet1.dx = 3;    
    }
    if (keyID === 40 ) { //down arrow 
        e.preventDefault();
        jet1.dy = 3;   

    }
    if (keyID === 37 ) { //left arrow 
           e.preventDefault();
          jet1.dx = -3; 
          jet1.direction = -1;
    }

if (keyID === 80 ) { // P
     
          if(pauseCounter == 0){
          pause = true;
          pauseCounter++;
        }
         else if(pauseCounter == 1){
          pause = false;
          pauseCounter = 0;
        }
    }

    if (keyID === 13 ) { //enter
         e.preventDefault();
         //alert(iiuu);
         gameStart = true;  
            if(endPress == true && bossDead == true){
         timerOn = false; 
       
         newScript.src = "game2.js";
window.document.body.appendChild(newScript); 
music.pause();
}  
    }

     if (keyID === 69 ) { //e
         e.preventDefault();
        

//if (canvasBg.parentNode) {
 // canvasBg.parentNode.removeChild(canvasBg);
 // canvasJet.parentNode.removeChild(canvasJet);
 // canvasBullet.parentNode.removeChild(canvasBullet);
//}

          gameStart = true;  
           
         timerOn = false; 
       
         newScript.src = "game2.js";
window.document.body.appendChild(newScript); 
music.pause();

    }


    if (keyID === 32) { // space
     
       e.preventDefault();
      
       if(shootCounter >= shootLimit){
        jet1.fire = true;
        shootCounter = 0;
       if(jet1.weapon == 0){
        shoot.play();
      }
    }
       
    }
}
}
function checkKeyUp(e) {
    var keyID = e.keyCode || e.which;
   if(timerOn == true){
    if (keyID === 38 ) { //up arrow 
     jet1.dy = 0; 
    }
    if (keyID === 39 ) { //right arrow 
      jet1.dx = 0; 
    }
    if (keyID === 40 ) { //down arrow 
      jet1.dy = 0; 
    }
    if (keyID === 37 ) { //left arrow 
      jet1.dx = 0; 
    }
    if (keyID === 32) { // space
        jet1.fire = false;  
    }
}
}

// end of event functions


#6 HappyCoder   Members   -  Reputation: 2664

Like
1Likes
Like

Posted 21 March 2013 - 11:29 AM

A trick you can do in javascript is wrap everything in a single function and that takes them all out of the global scope.

So lets say you have all of the following global variables declared as such.
var a = 0;
var b = 1;

function doStuff()
{
    ++a;
}
...
You can wrap that code like this
function GameOne()
{
   var a = 0;
   var b = 1;

   function doStuff()
   {
       ++a;
   }
   ...
}
Now all of those variables are local variables to a function so there will be no conflicts. Then to run the code you simply call the function.
GameOne();
If you want to jump between games you will have to ensure that the first game you are coming from cleans up its event listeners and that its game loop exits.

This hack would seem to be a quick solution to your current problem, although I wouldn't recommend this solution for any new projects you start. Doing it this way requires you to reimplement your game loop and other code in every source file. Ideally you want to get rid of any duplicate code.

And if you need to get any local variables you can add a getter.
function GameOne()
{
   var a = 0;
   ...

   GameOne.getA = function()
   {
      return a;
   }
}
Then to use the getter you simply call GameOne.getA().

Edited by HappyCoder, 21 March 2013 - 11:30 AM.


#7 Patriarch K   Members   -  Reputation: 212

Like
0Likes
Like

Posted 21 March 2013 - 12:27 PM

Hmm, I wrapped it all around, but I can not from the main.js just write GameOne(); when I press a key because it cannot reach it? Or how did you mean with that? smile.png

 

EDIT: Hmm, it worked better when I included the game.js in the index file...of course! Thanks!! I will try this method and see if it's "waterproof" for at least my game.


Edited by Patriarch K, 21 March 2013 - 12:33 PM.


#8 Patriarch K   Members   -  Reputation: 212

Like
1Likes
Like

Posted 21 March 2013 - 01:39 PM

At the moment I use booleans in the menu called level1 = false and so on. I wrap these booleans around the loop-function in every game file and it works. If I use the google debugging it doesn't cost too much. Is this a good method or is it awkward? It works fine at the moment at least.

 

Is there a way to run a function only once and then quit it afterwards in my main script without touching the game.js?

For example, if I do like this:

 

KEY PRESS ENTER{

switch(level)

case 1:

level1();

break;

 

case 2:

level2();

etc etc....

 

If I have it like that in the main function then it will of course run the level you pick. But when you've completed that level. Then that level has already started.

The same if i put the switch statements in the loop. Then it will run multiple times (or only one time if I use a boolean on it). But I still can't quit it.

 

Is this something I have to do in the level-files?


Edited by Patriarch K, 21 March 2013 - 02:48 PM.


#9 Barzai   GDNet+   -  Reputation: 641

Like
0Likes
Like

Posted 21 March 2013 - 11:46 PM

Well, I'm still very much a beginner myself, but I'll post the way I go about it on the chance that some of my approach may be useful.  I'm not using much by way of HTML5, like canvas or anything as of yet.  Really the only more modern tags I use are outerWidth, innerWidth, and the height versions of those.

 

I make a general game object prototype, like this:

function GameSpace(gameGrid, playerArray, motionArray, frozenArray, timeStep, data, defaults) {
   this.gameGrid = gameGrid;
   this.playerArray = playerArray;
   this.motionArray = motionArray;
   this.frozenArray = frozenArray;
   this.timeStep = timeStep;
   this.data = data;
   this.defaults = defaults;
}

 

The gameGrid is my collision grid for that gamespace.  The arrays hold objects of the given types.  The timestep is a timestep :)  The thing that maybe applies here are the data and defaults objects.  Their only job is to store variables.  The defaults never gets rewritten after startup.  The data object variables can be rewritten from a hidden form in the web page.  If I mess things up too badly when I'm trying to tune stuff, I can restore the original configuration by resetting the data object to the values in the defaults object.

 

Then I make my actual game object, like:

var spaceInvadersGame = new GameSpace({}, [], [], [], 0, {}, {});
var activeGameSpace = spaceInvadersGame;

 

OF course there's other code elsewhere for actually writing the variables into the data object.

 

I can then access any variables for any gamespace I need in my functions by using activeGameSpace set to the game I want.  For example, the number of lives for the player would be:

activeGameSpace.data.lives

 

And the number of horizontal divisions I divide my game area into is:

activeGameSpace.gameGrid.horizontalDivisions

 

I can code that in my functions, and as long as I'm careful with naming it sort of works like polymorphism.  Whatever I set activeGameSpace to is the source of the variables in the data object the function calls.

 

I know that isn't particularly pretty, but javascript lets you get away with it.

 

This solves the problem with global collisions that hit javascript all the time.  It ignores the other potential issues, though, like accessing the same variables from many locations.  I try to avoid those problems by doing my best to use the data object mostly for things that look like constants to the gameSpace scope, if that makes sense.

 

I think your booleans solve the same problem in a slightly different way, though.  I'm using one variable, activeGameSpace, to point to all of my other variables, and you're using booleans to tell functions what variables to use.  I'd say your approach is probably just as good as mine.  Actually, I've learned plenty by reading your code.  I always find it educational to read other people's code.

 

Actually, your question about your loop makes me wonder if I should have my own timestep in my gamespace rather than making it global.  From what I understand the timer should regulate taking in inputs, stepping through game information, and drawing stuff.  That might be better left as a global rather than being part of a specific game space.  I haven't tried loading multiple games from one webpage with a dropdown menu yet.  That may be a problem that arises when I do.

 

Anyway, I rambled a bit.  I hope some of that was useful.  And, again, I'm still learning myself, so there could be some big errors I don't know about in my approach.

 

Cheers






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS