Kids

Can

JavaScript

<-----Back        Next --->

Objects in Arrays


In many games you need to handle many objects at the same time and do similar things to all of them. For instance: you will want to create a couple of the same Objects , and then draw them all.
Arrays and For-loops will help you do all these things efficiently.

example1:

For loops and Arrays

The For loop executes code a number of times,
It runs from a startvalue: i=0, till an endvalue: i<3. After each loop, i increases by 1:i++

An Array is a special object that can hold all types of elements.
You can find the objects again in the Array with their index-number:i (postion).

In this For loop, a new ship Object is made and put into shipsArray[0], shipsArray[1], shipsArray[2]

 for ( 
 i = 0  
 ; 
 i < 3 
 ; 
 i++ 
 ){ 
  


 shipsArray 
 [ 
 i 
 ] 
 = 
 new  
 readyObjWithAnim( 
 myImg,0, 
 i*50, 
 60,40 
 ) 


 shipsArray 
 [ 
 i 
 ] 
 . 
 animate() 
 ; 
 } 

In the draw function we use a For Loop to draw each element in the shipArray.
It runs from the first i=0 to the last element i < shipsArray.length of the shipsArray;

 function draw() { 


 for ( 
 i = 0  
 ; 
 i < 
  shipsArray 
 . 
  length 
 ; 
 i++ 
 ) 
 { 


  shipsArray 
 [ 
 i 
 ] 
 . 
 draw() ; 
 } 
 } 

For more detailed information on For Loops and Arrays click here.

Use For loops and Arrays ......... .... "TryoutPanel1"
<script> var canvas= document.getElementById('canvas'); var context; var shipsArray=new Array(); ////////////////////////// SHIP OBJECT ////////////////////////////////////////////////// function Ship(img,x,y,width,height){ // constructor Ship this.img=img; this.x=x; this.y=y; this.width=width; this.height=height; this.stop=false; // boolean: stop this.draw= function(){ // Ships draw function context.drawImage(this.img,this.x,this.y,this.width,this.height); } //***********************************************// this.animate= function(){ // Ship animate function if(this.stop==false){ // check if ship is stopped if(this.x> canvas.width || this.x<0){ //stop instance when x,y outside canvas this.stop=true; // stop animation var i=shipsArray.indexOf(this); // get index of this ship shipsArray.splice(i,1); // delete this ship from shipsArray } //*************************************************// this.x += 20; // changes the x, y coordinates. draw(); setTimeout(this.animate.bind(this),200); // timeout loop } } } ////////////////////////////CREATE INSTANCES , IMAGES + START//////////////////////////////////////// var shipImg=new Image(); //create new image shipImg.src="/pics/greyship.png"; draw(); // call draw before animate, or canvas is undefined for(var i=0;i<3;i++){ //.... change this for loop var ship= new Ship(shipImg,0,i*50, 40,30); // make a new ship Object ship.animate(); // let it animate shipsArray.push(ship); // put ship in shiparray } ////////////////////// MAKE A SHIPSENDING FUNCTION//////////////// function shipsender(){ // look at the for-loop for help //.......make a new Ship //.......let it animate //.......put it in the shipArray //.......make a loop with setTimeout(shipsender,1000) // don't forget to call shipsender(); after draw(); } ////////////////////////////DRAW WHOLE CANVAS////////////////////////////////////////////////// function draw(){ // draw whole canvas function canvas=document.getElementById('canvas'); context=canvas.getContext('2d'); context.clearRect(0,0,canvas.width,canvas.height); // wipe canvas for(var i=0;i<shipsArray.length;i++){ // for all elements in shipsArray shipsArray[i].draw() // draw number [i] of shipsArray } //..... make another for loop with e.g. : context.strokeText('Hello',i*30,i*30); } </script> <p>Use for loops and the shipArray to create lots of ships:</p> <canvas id="canvas" width="450" height="300" style="border:1px solid" tabindex="0" ></canvas> <br> <ul><li>Change the for loop, to make a different number of ships(53)</li> <li>Make another for loop in DRAW function(82)</li> <li>Make a <b>shipsender function</b>(63)</li>




Finish Game

example2:




The Game in the Tryout-panel misses some For-loops. In the draw function it needs to draw all the ships in shipsArray.


Make SpaceBattle Game......... .... "TryoutPanel2"
<script> var canvas; var context; var shipsArray=new Array(); var bulletArray= new Array(); var gameover=false; var points=0; ///////////////////// KEYS FUNCTION TO MOVE MARTIAN SHIP//////////////////////////////////// function keysFunction(){ //defines what the keys will do var key=event.keyCode; if(key==39){ // right arrow martian.x+=50; draw(); } else if(key==37){ // left arrow martian.x-=50; draw(); } else if(key==32){ // space bar : SHOOT event.preventDefault(); // otherwise window scrolls var bullet=new Bullet((martian.x+(martian.width/2)),martian.y-11); bulletArray.push(bullet); // create a bullet and put in ARRAY draw(); bullet.animate(); } } /////////// BULLET CONSTRUCTOR ///////////////////////////////// function Bullet(x,y){ this.x= x; this.y= y; this.width=5; this.height=5; this.dy=-1 // y-direction this.stop=false; // boolean: stop //*********************** DRAW **************************// this.draw= function(){ circle(this.x,this.y,this.width); } //******************** ANIMATE ******************************// this.animate = function(){ if(this.stop==false){ // check if bullet is not stopped if(this.y<100){this.dy*=-1;} //bullets fall down when they reach y=100 this.y+=this.dy*20; if(this.y>canvas.height){this.stop=true;} // stop bullet when at bottom of canvas draw(); // draw whole canvas for(var i=0;i<shipsArray.length;i++){ // check if bullet hits ships in shipArray if(intersects(this,shipsArray[i])){ // if ship is shot this.stop=true; // stop this bullet shipsArray[i].stop=true; // stop ship points+=10; // add points } } ///.......... write a similar if statement to check if bullet hits martian(look at 70) //... use intersects(this,martian) and gameover=true; setTimeout(this.animate.bind(this),100); // timeout Loop } else{ // if bullet.stop==true var i= bulletArray.indexOf(this); // get bullet index bulletArray.splice(i,1); // delete this bullet from Array } } ///************************************************************ } ////////////////////////////CIRCLE////////////////////////// function circle(x,y,radius) { // circle context.fillStyle='blue'; context.beginPath(); context.arc(x, y, radius,0, Math.PI*2, true); context.fill(); context.stroke(); } ////////////////////// SHIP: READY OBJECT WITH ANIMATION////////////////////////////////////////////////// function Ship(img,x,y,width,height){ // constructor SHIP this.img=img; this.x=x; this.y=y; this.width=width; this.height=height; this.stop=false; // boolean: stop ///******************** DRAW ******************************// this.draw= function(){ // Ship draw function context.drawImage(this.img,this.x,this.y,this.width,this.height); } ///******************** ANIMATE ******************************// this.animate= function(){ // Ship animate function if(this.stop==false){ // if ship is not stopped if(this.x> canvas.width ){ //if ship.x escapes outside canvas this.stop=true; // stop animation ///.........write code to loose points when ship escapes: points -= 10; } this.x += 20; // moves ship to the right . //..........Try random up and down y-movement, use: Math.ceil(Math.random()*50)-25; draw(); setTimeout(this.animate.bind(this),200); // timeout loop } else{ // if stopped var i= shipsArray.indexOf(this); shipsArray.splice(i,1); // delete this bullet from Array } } //************************************************************** } ////////////////////////////////////INTERSECTS//////////////////////////// function intersects(obj1, obj2) { // checks if 2 shapes intersect if (obj1.x > (obj2.x + obj2.width) || obj2.x > (obj1.x + obj1.width)) {return false;} if (obj1.y > (obj2.y + obj2.height) || obj2.y > (obj1.y + obj1.height)) {return false; } return true; // when both above conditions are not true, the shapes must intersect } ////////////// SHIPSENDER //////////////////////////////// function shipSender(){ if(gameover==false){ /// check if still playing var ship= new Ship(greyShipImg,0,100, 40,30); // new ship shipsArray.push(ship); // put in Array ship.animate(); // make it move setTimeout(shipSender,2000); // this Loop will send a ship every 2000 millisec } } ///////////////////// CREATE INSTANCES //////////////////////// var martianImg=new Image(); //create new image martianImg.src="/pics/spaceship.gif"; // change your image var martian=new Ship(martianImg,200,230, 70,70); var greyShipImg=new Image(); //create new image greyShipImg.src="/pics/greyship.png"; /////////////////////// WHOLE CANVAS DRAW FUNCTION //////////////////////// function draw(){ // draw whole canvas function canvas=document.getElementById('canvas'); context=canvas.getContext('2d'); context.clearRect(0,0,canvas.width,canvas.height); // wipe canvas martian.draw(); // draw the martian ship for (var i=0;i<bulletArray.length; i++){ // draw all bullets in Array bulletArray[i].draw(); } //.......... write a for-loop to draw all ships in shipsArray context.font='20px Georgia'; context.fillText(points,10,30); // write the points on canvas //..... write an if statement that writes GAMEOVER when you loose:if (gameover){...} } /////////// STOP /////////////////////// function stop(){ ///............. write a for-loop to make all ships in shipsArray stop (someShip.stop=true); } ///////////////////// START ALL /////////////////////////////////// draw(); canvas.focus(); shipSender(); </script> <p><b>Move left-right:</b> arrow keys <b>Shoot</b>:space bar .<br></p> <canvas id="canvas" width="500" height="300" onkeydown="keysFunction();" ondblclick="toggleStartStop();"tabindex="0"></canvas> <p> You can't see the ships, because the draw function is not drawing them. </p> <ul><li>Write a <b>for-loop</b> to draw all ships in shipsArray(215)</li> <li>Write an <b>if-statement</b> to check if a Bullet hits the martian ship(77)</li> <li>Write code to loose points when the grey ships escape(134)</li> <li>For more suggestion find all greens</li></ul>





<-----Back        Next --->

This username already exists.

This username already exists.

Login or register to save your work.

User name field is empty.

Your username needs to be at least 7 characters long.

Your username can not contain any of the following characters: ",', <, > , < and whitespaces.

Please enter a correct email addresss .

This email address is not found in our database .

Your password needs to be at least 7 characters long.

login
username
password
forgot password
email
register
username
password
email