Code-editors usually have an Intellisense function.
It pops up all variables,methods and properties that are available to you in that part of the code:
select/click them and they appear in the code-panel
There are 2 ways to call the Intellisense:CTRL+SPACE and dot.
press: CTRL+Space
n
press: CTRL+Space
type :
person1
.
person1
.
a
press: CTRL+Space
Try Intellisense ......... .... "TryoutPanel1"
<script>
var person1= {name:'Krimson',age:13};
var firstName = 'Melinda';
var nameArray= ['John','Helen','Thomas'];
//.... Before the comment press CTRL+SPACE: You will see all current global variables and functions.
// the variables (properties) belong with the object window.
//.... type nCTRL+SPACE : You will see all properties starting with n
//....type person1. :You will see the properties belonging with the person1 object
//.... type firstname. :You will see all functions and properties belonging with String
// because firstName is a String
//....type nameArray. :You will see all functions and properties for Array
</script>
<p id="topP">Let's try out Intellisense.</p>
<ul><li>Before the comment. Press <b>CTRL+SPACE</b> (6)<br>
You will see all current <b>global variables</b>
and functions.<br> The ones that were made in the script,
but also the properties that <b>belong with this window object</b></li>
<li> To see the value of a variable's property you can type: alert(person1.name);
Then execute.</li>
<li> type <b>nCTRL+SPACE</b> : You will see all properties <b>starting with n </b> (8)</li>
<li>To see properties and functions of the variables type: <b>variableName.</b> (10,11,13)</li>
</ul>
click here for more info about the difference between global and local variables
and their accessibility.
In the Tryout Panel below there is a new Frog object that is called frog.
The right key makes him move to the right. Use intellisense to find out what else he can do
and make the other keys work.
To find the keyCode for a key:Type a key in the input field below.
<script>
var canvas;
var context;
var animation;
var points=0;
var lifes=3;
var thingsToDrawArray=[];
///ADD POINT
function addPoint() {
points+=5;
}
///GAME OVER
function gameover(){ /// clear animations
lifes=0;
clearTimeout(animation);
stop();}
// DELETELIFE
function deleteLife(){
lifes-=1; // take life off
if(lifes<=0){return true;} // if 0 lifes: gameover()
else{return false;}
}
/////////////////////////////////// FROG //////////////////////////////////////////////////
function Frog(img,x,y,width,height){ // constructor ReadyObj
this.img=img;
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.speed=30;
this.dx=1; // direction on x-axis: +1 or -1
this.dy=1; // .............y-axis: ........
this.jumpHeight=30;
this.jumpWidth=5;
this.deltaA=90; // keeps track of angle for jump() function
this.stop=false; // boolean stop: if true can't move
var that= this;
//RIGHT
this.right=function(){
this.dx=1;
this.img=frogRightImg;
};
//LEFT
this.left=function(){
this.dx=-1;
this.img=frogLeftImg;
};
///DRAW
this.draw= function(){ // draw function
context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord
};
//MOVE
this.move=function(){
if(!this.stop ){
if(this.dx < 0 && this.x+this.dx*this.speed>=0) this.x += this.dx*this.speed; // changes the x, y coordinates.
if ( this.dx > 0 && this.x+this.width+this.dx*this.speed<= canvas.width) this.x += this.dx*this.speed;
}
};
///EAT
this.eat=function(){
this.tongue=new Tongue(this);
thingsToDrawArray.unshift(this.tongue); // put tongue at first postion of things to Draw
this.tongue.rollout();
};
//// JUMP
this.jump=function(){ // frog jumps
if(!this.stop){ // make sure he doesn't jump when he is killed
if (this.dx>0){this.img=frogJump1Img;}
else{this.img=frogJump2Img;}
this.dy=-(Math.sin(this.deltaA * (Math.PI/180))); // dy becomes sine from deltaA (a changing angle)
this.x+=this.dx*this.jumpWidth;
this.y+=this.dy*this.jumpHeight;
this.height=200;
draw();
this.deltaA+=10; // keep track of angle
if(this.deltaA<271) /// from 90-270
{setTimeout(this.jump.bind(this),50);} //// loop
else{this.deltaA=90; this.height=90; // end of jump
this.jumpHeight=30;this.jumpWidth=5; // in case jumpheight changed, put back
if (this.dx>0){this.img=frogRightImg;}
else{this.img=frogLeftImg;} // change img to sitting img
}
}
};
}// end of FROG
///////// TONGUE //////////////////////////////////
Tongue= function (owner){ // inner function
this.owner=owner;
this.height=20;
this.width=7;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
this.draw= function(){
context.fillStyle='red';
context.fillRect(this.x, this.y,this.width,this.height); //draw rect for a tongue
}
/// ROLLOUT
this.rollout=function(){
this.height+=5;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
if(this.height<100){
setTimeout(this.rollout.bind(this),25);
}
else { this.owner.tongue=null;
thingsToDrawArray.splice(thingsToDrawArray.indexOf(this),1);
// when bigger then 140
}
};
}
////////////////////////////////////INTERSECTS////////////////////////////
function intersects(obj1, obj2) { // checks if 2 shapes intersect
if (obj1.x > (obj2.x + obj2.width*0.7) || obj2.x > (obj1.x + obj1.width*0.7)) {return false;}
if (obj1.y > (obj2.y + obj2.height*0.7) || obj2.y > (obj1.y + obj1.height*0.7)) {return false; }
return true;
}
///////////////////////////////////////KEYS FUNCTION////////////////////////////////
function keysFunction(){ //defines what the keys will do
var key=event.keyCode;
if(key==39){ // right arrow
frog.right(); // frog turns right
frog.move(); // frog moves
}
else if(key==37){ // left arrow
//............type: frog. and choose an action for frog
// action are functions. they end with (): move()
}
else if(key==38){ // up arrow
event.preventDefault(); // otherwise window scrolls
//............type frog. and choose the function you want frog to do
}
else if(key==32){ // space
event.preventDefault(); // otherwise window scrolls
//......if you want to see the value of frog's properties
//...... type e.g. alert(frog.width)
//what happens if you change some properties
}
}
/////////////////////////////////////CREATE IMAGES ////////////////////////////////////////
var frogRightImg=new Image(); //create new image
frogRightImg.src="/pics/frog1.png"; // give it a new src
var frogLeftImg=new Image(); //create new image
frogLeftImg.src="/pics/frog2.png"; // give it a new src
var frogJump1Img=new Image(); //create new image
frogJump1Img.src="/pics/frog-jump1.png"; // give it a new src
var frogJump2Img=new Image(); //create new image
frogJump2Img.src="/pics/frog-jump2.png"; // give it a new src
// DECLARE A GLOBAL VARIABLE
var frog; // declare a global variable for frog so it is accessible in all functions
///////////////////////////// INITIALIZE variables that change///////////////////////////
function initialize(){
canvas=document.getElementById('canvas');
lifes=3; // put the lifes and points back to start values
points=0;
frog=new Frog(frogRightImg,300,canvas.height-100, 90,90); // Frog(img,x,y,width,height)
thingsToDrawArray=[frog]; // add frog to thingsToDrawArray, or it won't be drawn on the canvas
}
///////////////////////////////////////DRAW WHOLE CANVAS//////////////////////////////////////////////////
/// DRAW
function draw(){ // draw whole canvas function
canvas=document.getElementById('canvas');
context=canvas.getContext('2d');
context.fillStyle='lightBlue';
context.fillRect(0,0,canvas.width,canvas.height); // wipe canvas
context.fillStyle='white';
context.font="25px Georgia";
context.fillText('Score:'+ points,400,30);
for(var i=0;i<thingsToDrawArray.length;i++){ // draw all things in the thingsToDrawArray
if(thingsToDrawArray[i]){thingsToDrawArray[i].draw();}
}
if(lifes>0){ /// if lifes left:draw lifes
context.fillText('LIFES:',5,30)
for(var i=0;i<lifes;i++){ /// draw frog images for each life in top left screen
context.drawImage(frogRightImg,i*30+100,5,25,25);
}
}
else{context.fillText('GAME OVER:',5,30) ;gameover(); } // no lifes: gameover();
}
///// ANIMATIONLOOP ///////// main loop
function animationLoop(){
draw(); // calls draw
animation=setTimeout(animationLoop,25); // then calls itself after 25 ms, creating a loop
}
///////////////////// STOP /////////////////////////
function stop(){
clearTimeout(animation);
for (var i = 0 ; i < thingsToDrawArray.length ; i++) {
if(thingsToDrawArray[i].deleteMe){
thingsToDrawArray[i].deleteMe();} // delete all animations from insects
}
}
///////////////////// RESTART /////////////////////////
function restart(){
stop();
initialize();
animationLoop();
}
initialize();
animationLoop();
canvas.focus();
</script>
<p id="topP">Here is <b>frog</b> all by himself. Only the <b>right arrow</b>key works.
Use the Intellisense function to make the other keys work</p>
<canvas id="canvas" width="600" height="400" tabindex="0" onkeydown="keysFunction()"
ondblclick= "restart()" onclick="stop()" title='double click to start'></canvas>
<ul><li>To make the <b>left-key</b> work Place the cursor in the <b>keysfunction</b>
inside else if(key==37) and type: <b>frog.</b>(167).
Intellisense will show all properties and functions for frog. </li>
<li>The <b>functions</b> are the <b>actions</b> frog can do. They end with <b>()</b> e.g. move().
Try out what they do, and choose funtions for the left-key</li>
<li>Now do the same for the <b>up key</b>(174)</li>
<li>Find out the values of frog's <b>properties </b> by typing e.g. <b>alert(frog.jumpHeight)</b> (180)</li>
<li>Change some <b>properties </b> and watch what happens (324)</li></ul>
Now tryout the possibilities of the Insects.
Space bar adds a new Insect(a nasty one). But it stands still.
Type bee. to find out what functions an insect has.
Play with Insect ......... .... "TryoutPanel3"
<script>
var canvas;
var context;
var animation;
var frog;
var points=0;
var lifes=3;
var yummiesArray;
var nastiesArray;
var attackTime=7000;
///////// INSECT /////////////////////////////////////////////
function Insect(x,y,kind){
var nastyImages=[beeImg,waspImg];
var yummyImages=[fly1Img,fly2Img,fly3Img,fly4Img,fly5Img,];
if(kind=='nasty'){
this.img=nastyImages[Math.floor( Math.random()* nastyImages.length)];
this.width=50;
this.height=50;
}
else{
this.img=yummyImages[Math.floor( Math.random()* yummyImages.length)];
this.width=40;
this.height=40;}
this.x=x;
this.y=y;
this.dx=1;
this.dy=1;
this.deltaT=0;
this.stop=false;
this.speed=12;
this.kind=kind;
//DRAW
this.draw= function(){ // draw function
context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image
};
////FLYBY
this.flyby= function(){ // Insect's animate function
if(this.kind=='nasty'){console.log('flyby');}
if(this.stop==false){ // check if animation is stopped
if((this.x + this.width) > canvas.width ){this.free()} //delete from array when escaping canvas horizontally
else{
this.x += this.dx * this.speed; // change yummy.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
if(this.kind=='nasty' && intersects(this,frog)){this.sting();deleteLife();}
else{ setTimeout(this.flyby.bind(this),100);} // timeout loop
}
}
};
////FLUTTER
this.flutter= function(){ // Insect's animate function
if(this.stop==false){ // check if animation is stopped
if( this.x <0 || (this.x+this.width) > canvas.width ){this.dx *= -1;} //turn around horizontally
this.x += this.dx * this.speed; // change insect.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
if(this.kind=='nasty' && intersects(frog,this)){this.stop=true;this.sting();deleteLife();}
else{ setTimeout(this.flutter.bind(this),100);} // timeout loop
}
};
////FLYROUND
this.flyround= function(){ // Insect's animate function
if(this.stop==false){ // check if animation is stopped
if(this.x > canvas.width ){this.x =0;} //come back on left side o canvas
else{
this.x += this.dx * this.speed; // change yummy.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
if(this.kind=='nasty' && intersects(frog,this)){this.stop=true;this.sting();deleteLife();}
else{ setTimeout(this.flyround.bind(this),100);} // timeout loop
}
}
};
////ZIGZAG
this.zigzag= function(){ // Insect's animate function
if(this.stop==false){ // check if animation is stopped
if(this.x > canvas.width ){this.x =0;} //come back on left side canvas
else{ this.x += this.dx * this.speed; } // change yummy.x-y pos
if(this.deltaT<700){ // keep going for 700 msec
this.deltaT+=100; // add on 100 msec to keep track of time
this.y += this.dy * this.speed; // change y position
}
else{this.deltaT =0; this.dy *=-1;} // after 700 msec turn y-direction
setTimeout(this.zigzag.bind(this),100); // timeout loop
}
};
////ATTACK
this.attack= function(){ // Insect's animate function
this.stop=true; // stop causes the other movements to stop
if( this.y <canvas.height-75){ // if insect is not above floor
this.y += this.speed; // fly down
}
else { // at the right height
this.x += this.dx * this.speed; // move horizontally
}
if(intersects(this,frog)){
deleteLife(); // deleteLife
this.sting(); // insect stings and dies
}
else if(this.x<0 || this.x>canvas.width){this.free();} // if insects flies outside canvas, delete him
else{ // otherwise
setTimeout(this.attack.bind(this),50); // repeat timeout loop
}
};
////ATTACK AFTER
this.attackAfter = function(time){
this.stop=true;
setTimeout(that.attack,time);
};
//FIND
this.find= function(object){ ///find function, changes insect's dx direction to follow the object
this.dx =(object.x-this.x)/ Math.abs(object.x-this.x); //gives sign of distance between frog and insect
};
//STING
this.sting=function(){
this.stop=true;
this.y-=8; /// go up
this.width+=5; /// enlarge
this.height+=5;
this.draw();
this.deltaT+=50; // keep track of time
if(this.deltaT<1300) /// if shorter the 1000 millisec
{setTimeout(this.sting.bind(this),50);} //// loop
else{
var index= nastiesArray.indexOf(this); // delete nasty from Array
if(index!=-1)
{nastiesArray.splice(index,1);}
}
}
///FREE
this.free=function(){
this.stop=true;
if(this.kind=='yummy'){yummiesArray.splice(yummiesArray.indexOf(this),1);delete this;
}
else if(this.kind=='nasty'){nastiesArray.splice(nastiesArray.indexOf(this),1);
console.log('nastiesArray.length:'+ nastiesArray.length);delete this;
}
};
}
/////////////////////////////////// FROG //////////////////////////////////////////////////
function Frog(img,x,y,width,height){ // constructor ReadyObj
this.img=img;
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.speed=30;
this.dx=1; // direction on x-axis: +1 or -1
this.dy=1; // .............y-axis: ........
this.jumpHeight=30;
this.jumpWidth=5;
this.deltaA=90; // keeps track of angle for jump() function
this.stop=false; // boolean stop: if true can't move
var that= this;
//RIGHT
this.right=function(){
this.dx=1;
this.img=frogRightImg;
};
//LEFT
this.left=function(){
this.dx=-1;
this.img=frogLeftImg;
};
///DRAW
this.draw= function(){ // draw function
context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord
};
//MOVE
this.move=function(){
if(!this.stop ){
if(this.dx < 0 && this.x+this.dx*this.speed>=0) this.x += this.dx*this.speed; // changes the x, y coordinates.
if ( this.dx > 0 && this.x+this.width+this.dx*this.speed<= canvas.width) this.x += this.dx*this.speed;
}
};
///EAT
this.eat=function(){
setTimeout(function(){
that.tongue=new Tongue(that);
that.tongue.rollout();},300);
};
//// JUMP
this.jump=function(){ // frog jumps
if(!this.stop){ // make sure he doesn't jump when he is killed
if (this.dx>0){this.img=frogJump1Img;}
else{this.img=frogJump2Img;}
this.dy=-(Math.sin(this.deltaA * (Math.PI/180))); // dy becomes sine from deltaA (a changing angle)
this.x+=this.dx*this.jumpWidth;
this.y+=this.dy*this.jumpHeight;
this.height=200;
this.draw();
this.deltaA+=10; // keep track of angle
if(this.deltaA<271) /// from 90-270
{setTimeout(this.jump.bind(this),50);} //// loop
else{this.deltaA=90; this.height=90; // end of jump
this.jumpHeight=30;this.jumpWidth=5; // in case jumpheight changed, put back
if (this.dx>0){this.img=frogRightImg;}
else{this.img=frogLeftImg;}
}
}
};
}// end of FROG
///////// TONGUE //////////////////////////////////
Tongue= function (owner){ // inner fucntion
this.owner=owner;
this.height=20;
this.width=7;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
this.draw= function(){
context.fillStyle='red';
context.fillRect(this.x, this.y,this.width,this.height); //draw rect for a tongue
}
/// ROLLOUT
this.rollout=function(){
this.height+=20;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
for(var i=0;i<yummiesArray.length;i++){ // for all yummies check if tongue hits them
if(intersects(this,yummiesArray[i])){
addPoint(); // add a point
yummiesArray[i].free(); // deletes this insect and creates new one
}
}
for(var i=0;i<nastiesArray.length;i++){ // for all nasties check if tongue hits them
if(intersects(this,nastiesArray[i])){
deleteLife(); // delete Life
}
}
if(this.height<140){
setTimeout(this.rollout.bind(this),50);
}
else{this.owner.tongue=null;delete this;} // delete tonque
}
}
////////////////////////////////////INTERSECTS////////////////////////////
function intersects(obj1, obj2) { // checks if 2 shapes intersect
if (obj1.x > (obj2.x + obj2.width*0.7) || obj2.x > (obj1.x + obj1.width*0.7)) {return false;}
if (obj1.y > (obj2.y + obj2.height*0.7) || obj2.y > (obj1.y + obj1.height*0.7)) {return false; }
return true;
}
///////////////////////////////////////KEYS FUNCTION////////////////////////////////
function keysFunction(){ //defines what the keys will do
var key=event.keyCode;
if(key==39){ // right arrow
frog.right(); // frog turns right
frog.move(); // frog moves
}
else if(key==37){ // left arrow
frog.left(); // frog turns left
frog.move(); // frog moves
}
else if(key==38){ // up arrow
event.preventDefault(); // otherwise window scrolls
frog.jump(); // frog jump
frog.eat(); // frog eat
}
else if(key==32){ // space
event.preventDefault(); // otherwise window scrolls
var bee=new Insect(0,Math.floor(Math.random()*100),'nasty'); // makes insect
nastiesArray.push(bee); // add to the nastiesArray, to draw it on canvas
//......type bee. to see all functions and properties of bee
//...... try out the functions and combinations
//...use some combinations of functions and or properties to make bee do cool stuff
}
}
/////////////////////////////////////CREATE IMAGES ////////////////////////////////////////
var frogRightImg=new Image(); //create new image
frogRightImg.src="/pics/frog1.png"; // give it a new src
var frogLeftImg=new Image(); //create new image
frogLeftImg.src="/pics/frog2.png"; // give it a new src
var frogJump1Img=new Image(); //create new image
frogJump1Img.src="/pics/frog-jump1.png"; // give it a new src
var frogJump2Img=new Image(); //create new image
frogJump2Img.src="/pics/frog-jump2.png"; // give it a new src
var fly1Img=new Image();
fly1Img.src='/pics/fly1.png';
var fly2Img=new Image();
fly2Img.src='/pics/fly2.png';
var fly3Img=new Image();
fly3Img.src='/pics/fly3.png';
var fly4Img=new Image();
fly4Img.src='/pics/fly4.png';
var fly5Img=new Image();
fly5Img.src='/pics/fly5.png';
var beeImg=new Image(); //create new image
beeImg.src="/pics/bee.png";
var waspImg=new Image(); //create new image
waspImg.src="/pics/wasp.png";
///////////////////////////// INITIALIZE variables that change///////////////////////////
function initialize(){
canvas=document.getElementById('canvas');
lifes=3;
attackTime=7000;
points=0;
frog=new Frog(frogRightImg,300,canvas.height-100, 90,90); // Frog(img,x,y,width,height)
yummiesArray=[];
nastiesArray=[];
//........add other instances
}
///////////////////////////////////////DRAW WHOLE CANVAS//////////////////////////////////////////////////
/// DRAW
function draw(){ // draw whole canvas function
canvas=document.getElementById('canvas');
context=canvas.getContext('2d');
context.fillStyle='lightBlue';
context.fillRect(0,0,canvas.width,canvas.height); // wipe canvas
context.fillStyle='white';
context.font="25px Georgia";
context.fillText('Score:'+ points,400,30);
for(var i=0;i<yummiesArray.length;i++){
yummiesArray[i].draw();
}
for(var i=0;i<nastiesArray.length;i++){
nastiesArray[i].draw();
}
// draw these instances
if(frog.tongue){frog.tongue.draw();}
frog.draw();
//......... draw another instance here
if(lifes>0){ /// if lifes left:draw lifes
context.fillText('LIFES:',5,30)
for(var i=0;i<lifes;i++){ /// draw frog images for each life in top left screen
context.drawImage(frogRightImg,i*30+100,5,25,25);
}
animation=setTimeout(draw,25);
}
else{context.fillText('GAME OVER:',5,30) ;gameover(); } // no lifes: gameover();
}
///////////////////// STOP /////////////////////////
function stop(){
window.highestTimeoutId = window.setTimeout(";"); /// gets rid of all running timeouts
for (var i = 0 ; i < window.highestTimeoutId ; i++)
{window.clearTimeout(i);
}
}
///////////////////// RESTART /////////////////////////
function restart(){
window.highestTimeoutId = window.setTimeout(";"); /// gets rid of all running timeouts
for (var i = 0 ; i < window.highestTimeoutId ; i++)
{window.clearTimeout(i);
}
initialize();
draw();
}
///ADD POINT
function addPoint() {
points+=5;
}
///GAME OVER
function gameover(){ /// clear animations
clearTimeout(animation);
setTimeout(stop,1000);}
// DELETELIFE
function deleteLife(){
lifes-=1; // take life off
if(lifes<=0){return true;} // if 0 lifes: gameover()
else{return false;}
}
////SENDERS
function yummiesSender (){
if(yummiesArray.length<7){
yummiesArray.push(new Insect(0,Math.ceil(Math.random()*100),'yummy'));
yummiesArray[yummiesArray.length-1].zigzag();}
var time=Math.ceil(Math.random()*5000);
setTimeout(yummiesSender,time);
}
function nastiesSender (){
if(nastiesArray.length<3){
nastiesArray.push(new Insect(0,Math.ceil(Math.random()*100),'nasty'));
nastiesArray[nastiesArray.length-1].flyby();}
var time=Math.ceil(Math.random()*5000);
setTimeout(nastiesSender,time);
}
function attacker(){
var nasty=nastiesArray[Math.floor(Math.random()*nastiesArray.length)];
if(nasty){nasty.find(frog);nasty.attack();}
attackTime-=100;
setTimeout(attacker,attackTime);
}
initialize();
draw();
canvas.focus()
</script>
<p id="topP">The <b>Space bar</b> adds an Insect. But it stands still. Use Intellisense to make the insects come to life.</p>
<canvas id="canvas" width="600" height="400" tabindex="0" onkeydown="keysFunction()"
ondblclick="restart()" onclick="stop()" title='double click to start'></canvas>
<ul>
<li>Each time you press <b>Space Bar</b> a new Insect is made.(327) But it stands still.
</li>
<li>Type <b>bee.</b> to see all the functions and properties for <b>bee</b> (330).
</li>
<li>try out the functions and find the value of properties : alert(bee.kind)</li>
<li>use some combinations of functions and or properties to make bee do cool stuff</li>
</ul>
To make a frog game you need a frog and some insects: declare them: var bee;
In the initialize function give them a value: bee= new Instect( 100,50,'nasty')
and some actions bee.zigzag().
In the animationLoop you determine how they interact. if(intersects(frog,bee){bee.deleteMe}
Initialize and Intersects ......... .... "TryoutPanel4"
<script>
var canvas=document.getElementById('canvas');
var context;
var animation;
var frog;
var points=0;
var lifes=3;
var thingsToDrawArray;
var attackTime=7000;
/////////////////////////////////////CREATE IMAGES ////////////////////////////////////////
var frogRightImg=new Image(); //create new image
frogRightImg.src="/pics/frog1.png"; // give it a new src
var frogLeftImg=new Image(); //create new image
frogLeftImg.src="/pics/frog2.png"; // give it a new src
var frogJump1Img=new Image(); //create new image
frogJump1Img.src="/pics/frog-jump1.png"; // give it a new src
var frogJump2Img=new Image(); //create new image
frogJump2Img.src="/pics/frog-jump2.png"; // give it a new src
var fly1Img=new Image();
fly1Img.src='/pics/fly1.png';
var fly2Img=new Image();
fly2Img.src='/pics/fly2.png';
var fly3Img=new Image();
fly3Img.src='/pics/fly3.png';
var fly4Img=new Image();
fly4Img.src='/pics/fly4.png';
var fly5Img=new Image();
fly5Img.src='/pics/fly5.png';
var beeImg=new Image(); //create new image
beeImg.src="/pics/bee.png";
var waspImg=new Image(); //create new image
waspImg.src="/pics/wasp.png";
////////////////////////////////////INTERSECTS////////////////////////////
function intersects(obj1, obj2) { // checks if 2 shapes intersect
if(obj1 && obj2 && !obj1.stop && !obj2.stop){ // check if objects exist and not dead
if (obj1.x > (obj2.x + obj2.width*0.7) || obj2.x > (obj1.x + obj1.width*0.7)) {return false;}
if (obj1.y > (obj2.y + obj2.height*0.7) || obj2.y > (obj1.y + obj1.height*0.7)) {return false; }
return true;
}
return false;
}
///////// INSECT /////////////////////////////////////////////
function Insect(x,y,kind){
var nastyImages=[beeImg,waspImg];
var yummyImages=[fly1Img,fly2Img,fly3Img,fly4Img,fly5Img];
if(kind=='nasty'){
this.img=nastyImages[Math.floor( Math.random()* nastyImages.length)];
this.width=50;
this.height=50;
}
else{
this.img=yummyImages[Math.floor( Math.random()* yummyImages.length)];
this.width=40;
this.height=40;}
this.x=x;
this.y=y;
this.dx=1;
this.dy=1;
this.deltaT=0;
this.stop=false;
this.attackMode=false;
this.attackMotion=undefined;
this.speed=12;
this.kind=kind;
var that=this;
//DRAW
this.draw= function(){ // draw function
context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image
};
////FLYBY
this.flyby= function(){ // Insect's animate function
if(this.stop==false && this.attackMode==false){ // check if animation is stopped
if((this.x + this.width) > canvas.width ){this.deleteMe()} //delete from array when escaping canvas horizontally
else{
this.x += this.dx * this.speed; // change yummy.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
setTimeout(this.flyby.bind(this),100); // timeout loop
}
}
};
////FLUTTER
this.flutter= function(){ // Insect's animate function
if(this.stop==false && this.attackMode==false){ // check if animation is stopped or in attack
if( this.x <0 || (this.x+this.width) > canvas.width ){this.dx *= -1;} //turn around horizontally
this.x += this.dx * this.speed; // change insect.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
setTimeout(this.flutter.bind(this),100); // timeout loop
}
};
////FLYROUND
this.flyround= function(){ // Insect's animate function
if(this.stop==false && this.attackMode==false){ // check if animation is stopped
if(this.x > canvas.width ){this.x =0;} //come back on left side o canvas
else{
this.x += this.dx * this.speed; // change yummy.x-y pos
this.y += (Math.ceil(Math.random()*3)-2) * this.speed;
setTimeout(this.flyround.bind(this),100);} // timeout loop
}
};
////ZIGZAG
this.zigzag= function(){ // Insect's animate function
if(this.stop==false && this.attackMode==false){ // check if animation is stopped or in attack
if(this.x > canvas.width ){this.x =0;} //come back on left side canvas
else{ this.x += this.dx * this.speed; } // change yummy.x-y pos
if(this.deltaT<700){ // keep going for 700 msec
this.deltaT+=100; // add on 100 msec to keep track of time
this.y += this.dy * this.speed; // change y position
}
else{this.deltaT =0; this.dy *=-1;} // after 700 msec turn y-direction
setTimeout(this.zigzag.bind(this),100); // timeout loop
}
};
////ATTACK
this.attack= function(){ // Insect's animate function
this.attackMode=true;
if(!this.stop){
if( this.y <canvas.height-75){ // if insect is not above floor
this.y += this.speed; // fly down
}
else { // at the right height
this.x += this.dx * this.speed; // move horizontally
}
if(this.x<0 || this.x +this.width >canvas.width){
this.x=0;this.y=100;this.dx =1;
this.attackMode=false;this.flyround();} // if insects flies outside canvas, delete him
else{ // otherwise
setTimeout(this.attack.bind(this),50); // repeat timeout loop
}
}
};
////ATTACK Every
this.attackEvery = function(time){ // time is in milliseconds
this.attackMotion=setTimeout(function (){that.attack(); that.attackEvery(time);},time); // attack and then create a loop every 'time' msec
};
//FIND
this.find= function(object){ ///find function, changes insect's dx direction to follow the object
this.dx =(object.x-this.x)/ Math.abs(object.x-this.x); //gives sign of distance between frog and insect
};
//STING
this.sting=function(){
this.stop=true;
clearTimeout(this.attackMode);
this.attackMode=undefined;
this.y-=8; /// go up
this.width+=5; /// enlarge
this.height+=5;
this.draw();
this.deltaT+=50; // keep track of time
if(this.deltaT<1300) /// if shorter the 1000 millisec
{setTimeout(this.sting.bind(this),50);} //// loop
else{
var index= thingsToDrawArray.indexOf(this); // delete nasty from Array
if(index!=-1)
{thingsToDrawArray.splice(index,1);}
}
};
///DeleteMe
this.deleteMe=function(){
this.stop=true;
clearTimeout(that.attackMode);
var index=thingsToDrawArray.indexOf(this);
if(index!=-1){
thingsToDrawArray.splice(index,1);
}
};
}
/////////////////////////////////// FROG //////////////////////////////////////////////////
function Frog(img,x,y,width,height){ // constructor ReadyObj
this.img=img;
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.speed=30;
this.dx=1; // direction on x-axis: +1 or -1
this.dy=1; // .............y-axis: ........
this.jumpHeight=30;
this.jumpWidth=5;
this.deltaA=90; // keeps track of angle for jump() function
this.stop=false; // boolean stop: if true can't move
this.tongue=null;
var that= this;
//RIGHT
this.right=function(){
this.dx=1;
this.img=frogRightImg;
};
//LEFT
this.left=function(){
this.dx=-1;
this.img=frogLeftImg;
};
///DRAW
this.draw= function(){ // draw function
context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord
};
//MOVE
this.move=function(){
if(!this.stop ){
if(this.dx < 0 && this.x+this.dx*this.speed>=0) this.x += this.dx*this.speed; // changes the x, y coordinates.
if ( this.dx > 0 && this.x+this.width+this.dx*this.speed<= canvas.width) this.x += this.dx*this.speed;
}
};
///EAT
this.eat=function(){
this.tongue=new Tongue(this);
thingsToDrawArray.unshift(this.tongue); // put tongue at first postion of things to Draw
this.tongue.rollout();
};
//// JUMP
this.jump=function(){ // frog jumps
if(!this.stop){ // make sure he doesn't jump when he is killed
if (this.dx>0){this.img=frogJump1Img;}
else{this.img=frogJump2Img;}
this.dy=-(Math.sin(this.deltaA * (Math.PI/180))); // dy becomes sine from deltaA (a changing angle)
this.x+=this.dx*this.jumpWidth;
this.y+=this.dy*this.jumpHeight;
this.height=200;
this.draw();
this.deltaA+=10; // keep track of angle
if(this.deltaA<271) /// from 90-270
{setTimeout(this.jump.bind(this),50);} //// loop
else{this.deltaA=90; this.height=90; // end of jump
this.jumpHeight=30;this.jumpWidth=5; // in case jumpheight changed, put back
if (this.dx>0){this.img=frogRightImg;}
else{this.img=frogLeftImg;} // change img to sitting img
}
}
};
}// end of FROG
///////// TONGUE //////////////////////////////////
Tongue= function (owner){ // inner function
this.owner=owner;
this.height=20;
this.width=7;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
this.draw= function(){
context.fillStyle='red';
context.fillRect(this.x, this.y,this.width,this.height); //draw rect for a tongue
}
/// ROLLOUT
this.rollout=function(){
this.height+=5;
this.x= this.owner.x+0.5*this.owner.width;
this.y=this.owner.y - this.height +40;
if(this.height<100){
setTimeout(this.rollout.bind(this),25);
}
else { this.owner.tongue=null;
thingsToDrawArray.splice(thingsToDrawArray.indexOf(this),1);
delete this; // when bigger then 140
}
}
}
///////////////////////////////////////KEYS FUNCTION////////////////////////////////
function keysFunction(){ //defines what the keys will do
var key=event.keyCode;
if(key==39){ // right arrow
frog.right(); // frog turns right
frog.move(); // frog moves
}
else if(key==37){ // left arrow
frog.left(); // frog turns left
frog.move(); // frog moves
}
else if(key==38){ // up arrow
event.preventDefault(); // otherwise window scrolls
frog.jump(); // frog jumps
frog.eat();
}
else if(key==32){ // space
event.preventDefault(); // otherwise window scrolls
// ... can you make frog jump even higher?
}
}
/////// CREATE GLOBAL VARIABLES OUTSIDE FUNCTION /////
var yummy1; // declare global variable
//..........// declare more insect variables
///////////////////////////// INITIALIZE variables that change///////////////////////////
function initialize(){
frog=new Frog(frogRightImg,300,canvas.height-100, 90,90); // Frog(img,x,y,width,height)
yummy1=new Insect(250,Math.floor(Math.random()*100),'yummy'); // make the variable name point to an Object
//......make the yummy insect move
//..........make a nasty
//....... make it move and attack
thingsToDrawArray=[yummy1,frog]; // .... add the new insects to the thingsToDrawArray
// the draw function will draw them in order, last one on top.
lifes=3; // shows how many lifes frog has left
points=0; // points collected
}
//////////ANIMATION LOOP////// basic animation loop calls draw() every 25 ms
function animationLoop(){
if(intersects(yummy1,frog.tongue)){ // check if the yummy insect intersect with the frog's tongue
yummy1.deleteMe(); // if so delete the insect
//..................what should happen when the frog has eaten the yummy? (press CTRL-SPACE)
// if you have more yummies, should they all get the same points?
}
// ....if you created a nasty insect, check if it intersects with frog
// .....if so, what should happen? points down ? delete a life? create new insects?
draw(); // calls draw
animation=setTimeout(animationLoop); // then calls itself after 25 ms, creating a loop
}
///////////////////////////////////////DRAW WHOLE CANVAS//////////////////////////////////////////////////
/// DRAW
function draw(){ // draw whole canvas function
canvas=document.getElementById('canvas');
context=canvas.getContext('2d');
context.fillStyle='lightBlue';
context.fillRect(0,0,canvas.width,canvas.height); // wipe canvas
context.fillStyle='white';
context.font="25px Georgia";
context.fillText('Score:'+ points,400,30);
for(var i=0;i<thingsToDrawArray.length;i++){
if(thingsToDrawArray[i]){ // check if this instance is not null
thingsToDrawArray[i].draw();
} // then draw it
}
if(lifes>0){ /// if lifes left:draw lifes
context.fillText('LIFES:',5,30)
for(var i=0;i<lifes;i++){ /// draw frog images for each life in top left screen
context.drawImage(frogRightImg,i*30+100,5,25,25);
}
}
else{context.fillText('GAME OVER:',5,30) ;gameover(); } // no lifes: gameover();
}
///////////////////// STOP /////////////////////////
function stop(){
clearTimeout(animation);
for (var i = 0 ; i < thingsToDrawArray.length ; i++) {
if(thingsToDrawArray[i].deleteMe){
thingsToDrawArray[i].deleteMe();} // delete all animations from insects
}
}
///////////////////// RESTART /////////////////////////
function restart(){
stop();
initialize();
animationLoop();
}
///ADD POINT
function addPoint() {
points+=5;
}
///GAME OVER
function gameover(){ /// clear animations
clearTimeout(animation);
setTimeout(stop,1000);}
// DELETELIFE
function deleteLife(){
lifes-=1; // take life off
if(lifes<=0){return true;} // if 0 lifes: gameover()
else{return false;}
}
initialize();
animationLoop();
canvas.focus()
</script>
<p id="topP">Time to make your very own Game: The keys work but there is only 1 insect.</p>
<canvas id="canvas" width="600" height="400" tabindex="0" onkeydown="keysFunction()"
ondblclick="restart()" onclick="stop()" title='double click to start,click stop'></canvas>
<ul><li>Define some <b>global variables</b> for your new insects. <br>
It is done <b>outside </b> a function, so all functions can access them.(364)</li>
<li> Inside <b> initialize()</b> you make the new variables into new insects with <b>new Insect(x,y,'yummy') or 'nasty'</b> (372)</li>
<li>Make them <b>move and maybe attack</b>(373)</li>
<li>Add them to the <b>thingsToDrawArray</b> or they wil not be drawn on the canvas.(375)</li>
Even though the insects are there and are moving, nothing happens when frog runs into them.
<li>In the <b>animationLoop</b> you can check who <b>intersects()</b> with whom (386)</li>
<li>Then decide <b>what should happen</b> if frog eats or bumps into an insect (388)</li>
<li>Do the same for your other insects (391,392)</li>
</ul>
Some variables and functions are global: they belong with the window instance.
They are accessible everywhere in the code, or when you type window. or this.
Some are local and are only accessible inside the scope of a function
Some belong with an instance . They are accessed with e.g.: mouse.
Vars and Functions that belong with a Constructor can be accessed inside Constructor with this.