Kids

Can

JavaScript

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

Program with Intellisense



On this page you will make a game like this, simply by programming with the intellisense function of the Tryout panels.

example1:


Intellisense Function

Code editors usually have an Intellisense function.
The Intellisense function reads what variables and functions there are in a piece of code.
It pops up all relevant options: 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 
                
 ad 
 press: CTRL+Space 


 type : 
  mouse 
 . 
                
 mouse.mo 
 press: CTRL+Space 

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.

 window.  
                
 this. 
                
 press: CTRL+Space 


  mouse 
 . 
                
 mouse.mo 
 press: CTRL+Space 


 function someName (){ 
 var a = 3; 
 press: CTRL+Space 
 } 


 function MouseObject(){ 
 this.x=3; 
 this. 
 } 

In the Tryout Panel below there is a Mouse Object, mouse instance, Treat Object, KeysFunction, addPoints, add and a few more. Use Intellisense to pop them up.
Inside the KeysFunction you can add code to control mouse with the keys.

To find the keyCode for a key:Type a key in the input field below.

for more information on keydown click here

Use Intellisense......... .... "TryoutPanel1"
<script> var canvas; var context; var animation; var mouse; var points=0; var treatsArray; ///////// TREAT //////////////////////////////// function Treat(x,y){ var imgArray=[wedgeImg,peanutImg,sausageImg,cupcakeImg,hotdogImg]; this.img=imgArray[Math.floor( Math.random()* imgArray.length)]; this.x=x; this.y=y; this.width=30; this.height=30; this.draw= function(){ // draw function context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord }; } /////////////////////////////////// MOUSE ////////////////////////////////////////////////// function Mouse(img,x,y,width,height){ // constructor ReadyObj this.img=img; this.x=x; this.y=y; this.width=width; this.height=height; this.dx=1; // direction on x-axis: +1 or -1 this.dy=1; // .............y-axis: ........ this.angle=0; // angle 0,90,180,270 this.stop=false; // boolean stop: if true can't move //TURN this.turn=function(angle){ this.angle=angle; this.dx=Math.cos(this.angle * (Math.PI/180)); // calculate direction coeficient this.dy=Math.sin(this.angle * (Math.PI/180)); }; //DRAW this.draw= function(){ // Mouse draw function context.save(); // save current coordinate system settings context.translate((this.x+this.width/2),(this.y+this.height/2)); // move canvas' pivotal point context.rotate(this.angle * (Math.PI/180)); // rotate coordinate system context.drawImage(this.img,(-1*this.width/2),(-1*this.height/2),this.width,this.height); //draw image over the(0,0) coord context.restore(); // change back to normal coordinate system setting }; //MOVE this.move=function(){ if(!this.stop){ this.x += this.dx*10; // changes the x, y coordinates. this.y += this.dy*10; draw(); } }; ///EAT this.eat=function(){ for(var i=0;i<treatsArray.length;i++){ // for all treats in the Array if(intersects(treatsArray[i],this)){ //if mouse on top of this treat treatsArray.splice(i,1); // delete this treat from array } } } } // end Mouse ///////////////////////////////////////KEYS FUNCTION//////////////////////////////// function keysFunction(){ //defines what the keys will do var key=event.keyCode; if(key==39){ // right arrow mouse.turn(0); // the mouse turns 0 degrees mouse.move(); // then it moves } //...........put cursor before comment:press CTRL+Space //...........you will see all accessible variables and functions. else if(key==37){ // left arrow //..........type: mouse. make mouse turn 180 degrees //..........type: mouse. make mouse move } else if(key==38){ // up arrow event.preventDefault(); // otherwise window scrolls //..........type: mouse. and choose a function //..........type: mouse. and choose a function } else if(key==40){ // down arrow event.preventDefault(); // otherwise window scrolls //..........use intellisense to program some behavior for mouse } if(key==32){ // space event.preventDefault(); // otherwise window scrolls //..........can you make mouse eat //..........can you add some points? // .........can you add a new treat? } } ////////////////////////////////////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; } /////////////////////////////////////CREATE IMAGES //////////////////////////////////////// var mouseImg=new Image(); //create new image mouseImg.src="/pics/mouse.png"; // give it a new src var wedgeImg=new Image(); wedgeImg.src='/pics/wedge.png'; var sausageImg=new Image(); sausageImg.src='/pics/sausage.png'; var hotdogImg=new Image(); hotdogImg.src='/pics/hotdog.png'; var cupcakeImg=new Image(); cupcakeImg.src='/pics/cupcake.png'; var peanutImg=new Image(); peanutImg.src='/pics/peanut.png'; ///////////////////////////// INITIALIZE variables that change/////////////////////////// function initialize(){ canvas=document.getElementById('canvas'); points=0; mouse=new Mouse(mouseImg,230,230,50,50); treatsArray=[]; // fill treatsArray with Treats for(var i=0;i<8;i++){ addTreat(); } //........add other instances } ///////////////////////////////////////DRAW WHOLE CANVAS////////////////////////////////////////////////// /// DRAW function draw(){ // draw whole canvas function canvas=document.getElementById('canvas'); context=canvas.getContext('2d'); context.fillStyle='black'; 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<treatsArray.length;i++){ // draw all treats in TreatArray treatsArray[i].draw(); } mouse.draw(); /// draw mouse //......... draw other instances here animation=setTimeout(draw,100); } ///ADD POINT function addPoint() { points+=5; } /// ADD TREAT function addTreat(){ // adds a Treat to the Array with random x,y treatsArray.push(new Treat(Math.floor(Math.random()* canvas.width/30) *30, Math.ceil(Math.random()* (canvas.height-30)/30) *30)); } ///////////////////// RESTART ///////////////////////// function restart(){ initialize(); draw(); } initialize(); draw(); </script> <p id="topP">Use the <b>Intellisense </b> function to program some code to make Mouse <b>move</b> and <b>eat</b> the treats. <canvas id="canvas" width="500" height="300" tabindex="0" onkeydown="keysFunction()" ondblclick="restart()" ></canvas> <br> <ul> Inside the keysFunction() only the right-arrow key works.(96) <li>Try intellisense by placing the cursor in an empty space and press <b>CTRL+SPACE</b>(99) <br>first you see all variables and function in <b>this code</b>. Then all varibles and function available in this <b>Window</b>. </li> <li>Type <b>mouse.</b> and you see all variables and functions that belong with <b>Mouse</b>(102)</li> <li>Make mouse <b>turn</b> and <b>move</b>(102,103)</li> <li>Make mouse <b>eat</b> them the treats(200)</li> <li>Keeps score with <b>addPoint()</b> (201) and add treats(202)</li> </ul>





CatNMouse Game

Now you are ready for a bigger game. The Tryout Panel below has all the Objects the CatNMouse Game needs.
The KeysFunction() does not control anything yet. Insert cat and mouse's functions one by inside the Space-key section from the KeysFunction, to try out what they do.


Make CatNMouse Game ......... .... "TryoutPanel2"
<script> var canvas; var context; var animation; var cat; var mouse; var points=0; var lifes=3; var treatsArray; var trapsArray; var holesArray; var mouseholeImg, hotdogImg, hissingImg,hissing_flippedImg, mouseImg, // images catImg,cupcakeImg,sausageImg,peanutImg,wedgeImg,mousetrapImg; ///////// TRAP function Trap(x,y){ var imgArray=[mousetrapImg]; this.img=imgArray[Math.floor( Math.random()* imgArray.length)]; this.x=x; this.y=y; this.width=70; this.height=50; this.dx=1; this.deltaT=0; //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 }; ///SPRING this.spring=function(){ var index= trapsArray.indexOf(this); // delete trap from Array if(index!=-1) {trapsArray.splice(index,1);} this.y-=8; /// go up this.width+=5; /// enlarge this.height+=5; this.draw(); this.deltaT+=50; // keep track of time if(this.deltaT<1000) /// if shorter the 1000 millisec {setTimeout(this.spring.bind(this),50);} //// loop else{ trapsArray.push(new Trap(Math.floor(Math.random()* (canvas.width-70)/70) *70, /// create new trap Math.ceil(Math.random()* (canvas.height-50)/50) *50)); } }; } ///////// TREAT //////////////////////////////// function Treat(x,y){ var imgArray=[wedgeImg,peanutImg,sausageImg,cupcakeImg,hotdogImg]; this.img=imgArray[Math.floor( Math.random()* imgArray.length)]; this.x=x; this.y=y; this.width=30; this.height=30; this.draw= function(){ // draw function context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord }; } ///////// HOLE //////////////////////////////// function Hole(x,y){ var imgArray=[mouseholeImg]; this.img=imgArray[Math.floor( Math.random()* imgArray.length)]; this.x=x; this.y=y; this.width=70; this.height=50; //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 }; } /////////////////////////////////// MOUSE ////////////////////////////////////////////////// function Mouse(img,x,y,width,height){ // constructor ReadyObj this.img=img; this.x=x; this.y=y; this.width=width; this.height=height; this.dx=1; // direction on x-axis: +1 or -1 this.dy=1; // .............y-axis: ........ this.angle=0; // angle 0,90,180,270 this.deltaT=0; // keeps track of time in run() function this.stop=false; // boolean stop: if true can't move //TURN this.turn=function(angle){ this.angle=angle; this.dx=Math.cos(this.angle * (Math.PI/180)); this.dy=Math.sin(this.angle * (Math.PI/180)); }; //DRAW this.draw= function(){ // ReadyObjWithAnim draw function context.save(); // save current coordinate system settings context.translate((this.x+this.width/2),(this.y+this.height/2)); // move canvas' pivotal point context.rotate(this.angle * (Math.PI/180)); // rotate coordinate system context.drawImage(this.img,(-1*this.width/2),(-1*this.height/2),this.width,this.height); //draw image over the(0,0) coord context.restore(); // change back to normal coordinate system setting }; //MOVE this.move=function(){ if(!this.stop ){ if(this.x+this.dx*10>=0 && this.x+this.width+this.dx*10<=canvas.width)this.x += this.dx*10; // changes the x, y coordinates. if(this.y+this.dy*10>=0 && this.y+this.height+this.dy*10<=canvas.height)this.y += this.dy*10; } }; ///EAT this.eat=function(){ for(var i=0;i<treatsArray.length;i++){ if(intersects(treatsArray[i],this)){ addPoint(); // add a point treatsArray.splice(i,1); // delete this treat from array treatsArray.push(new Treat(Math.floor(Math.random()* canvas.width/30) *30, Math.ceil(Math.random()* (canvas.height-30)/30) *30)); } } } //////////TRAPS CHeCK this.trapsCheck=function(){ for(var i=0;i<trapsArray.length;i++){ // for all traps in trapsArray if(intersects(trapsArray[i],this)){ // check if it intersects with this mouse trapsArray[i].spring(); // make trap spring deleteLife(); // delete a mouse Life } } } ////////// ENTER HOLE this.enterHole=function(){ for(var i=0;i<holesArray.length;i++){ // for all holes in holessArray if(intersects(holesArray[i],this)){ // check if it intersects with this mouse i=(i+1==holesArray.length)?0:i+1; this.x=holesArray[i].x+10; // make mouse.x-y pos same as next hole in array this.y=holesArray[i].y+10; } }; } //// RUN this.run=function(){ // mouse speeds up if(!this.stop){ // make sure he doesn't run when he is killed this.move(); this.draw(); this.deltaT+=50; // keep track of time if(this.deltaT<500) /// if shorter the 1000 millisec {setTimeout(this.run.bind(this),50);} //// loop else{this.deltaT=0} } }; } //////////// CAT /////////////////////////////////// function Cat(img,x,y,width,height){ // constructor ReadyObj this.img=img; this.x=x; this.y=y; this.width=width; this.height=height; this.dx=-1; // direction on x-axis: +1 or -1 this.dy=1; // .............y-axis: ........ this.angle=0; // angle 0,90,180,270 this.speed=5; this.baseSpeed=5; this.pounceSpeed=20; this.angle=0; this.hissing=false; this.sniffTime=3000; var that= this; this.stop=false; // boolean stop: if true animation-loop is interupted // POUNCE this.pounce=function(){ this.hiss(); // make cat hiss this.speed=this.pounceSpeed; // speed becomes faster this.baseSpeed+=1 // every time cat pounces he speeds up setTimeout(function(){that.speed=that.baseSpeed;that.justEyes();},700); // after 1 sec turn back to normal }; //HISS this.hiss=function(){ // Cat's his function this.img=(this.dx>0)?hissingImg:hissing_flippedImg; // change the picture this.hissing=true; this.width=100; // enlarge picture this.height =100; }; //JUSTEYES this.justEyes=function(){ // Cat's justEyes function this.hissing=false; this.img=catImg; // back to normal eyes-picture this.width=80; // normal size this.height =40; }; //EAT this.eat=function(object){ this.stop=true; // stop cat from moving this.hiss(); // make him hiss this.width=120; // enlarge this.height=120; // position cat around mouse this.x=(this.img==hissingImg)? object.x-this.width/2:object.x-this.width/4; this.y=object.y-this.height/2; ////DRAW this.draw(); // draw cat object.stop=true; object.width*=0.8; // make it smaller to fit object.height*=0.8; object.draw(); // draw object var over=deleteLife(); // take of life and check for game over if(!over)setTimeout(reset,1000); // if lifes left: start up cat and mouse }; //FIND this.find= function(object){ /// Cat's find function, finds location of an object var cos=(object.x+object.width/2)-(this.x+this.width/2); // calculate x-distance from Cat to object var sin=(object.y+object.height/2)-(this.y+this.height/2); // calculate y-distance from Cat to object var hyp= Math.sqrt(Math.pow(cos,2)+ Math.pow(sin,2)); // calculate hypothenuse this.dx=cos/hyp; // set dx, dy to cos and sin this.dy=sin/hyp; }; ////ANIMATE this.animate= function(){ // Cat's animate function if(this.stop==false){ // check if animation is stopped if((this.x + this.width+10) > canvas.width || this.x <0 ){this.dx*=-1;} //turn around when escaping canvas horizontally if ((this.y + this.height+10) > canvas.height || this.y <0 ){this.dy *=-1;} //turn around when escaping canvas vertically this.x += this.dx * this.speed; // change cat.x-y pos this.y += this.dy * this.speed; if(intersects(this, mouse)){this.eat(mouse);} else{ setTimeout(this.animate.bind(this),100);} // timeout loop } }; //AUTOSTALK this.autoStalk=function(){ // cat sniffs out mouse and findsthe right direction this.find(mouse); if(this.sniffTime>400){ this.sniffTime-=150;} // sniffTime decreases if(! this.stop){setTimeout(function(){that.autoStalk(mouse);},that.sniffTime); } }; ///DRAW this.draw= function(){ // draw function if(this.hissing){ if(this.dx<0)this.img=hissing_flippedImg; else if(this.dx>0)this.img=hissingImg;} context.drawImage(this.img,this.x,this.y,this.width,this.height); //draw image over the(0,0) coord }; } ////////////////////////////////////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==32){ // space event.preventDefault(); // otherwise window scrolls //..... tryout all functions for cat--type: cat. //..... tryout mouse functions--type: mouse. trapsCheck() and enterHole() only work when mouse stands on top //..... the traps are in trapsArray. tryout its functions with :trapsArray[1]. // ....tryout addPoint() restart() reset() gameover() deleteLife() // .....now decide what you want to happen if space is pressed } else if(key==38){ // up arrow event.preventDefault(); // otherwise window scrolls /// .......make mouse turn(), move() and trapsCheck() } else if(key==40){ // down arrow event.preventDefault(); // otherwise window scrolls /// .......make mouse turn(), move() and trapsCheck() } else if(key==39){ // right arrow /// .......make mouse turn(), move() and trapsCheck() } else if(key==37){ // left arrow /// .......make mouse turn(), move() and trapsCheck() } //...make an Enter section and make it do stuff(enter key==13) } /////////////////////////////////////CREATE IMAGES //////////////////////////////////////// var tigerImg=new Image(); //create new image tigerImg.src="/pics/blackyAttack.gif "; var hissingImg=new Image(); //create new image hissingImg.src="/pics/cat-hissing.png" ; var hissing_flippedImg=new Image(); //create new image hissing_flippedImg.src="/pics/cat-hissing-flipped.png" ; var catImg=new Image(); //create new image catImg.src="/pics/cateye.png"; var mouseImg=new Image(); //create new image mouseImg.src="/pics/mouse.png"; // give it a new src var wedgeImg=new Image(); wedgeImg.src='/pics/wedge.png'; var sausageImg=new Image(); sausageImg.src='/pics/sausage.png'; var hotdogImg=new Image(); hotdogImg.src='/pics/hotdog.png'; var cupcakeImg=new Image(); cupcakeImg.src='/pics/cupcake.png'; var peanutImg=new Image(); peanutImg.src='/pics/peanut.png'; var mousetrapImg=new Image(); //create new image mousetrapImg.src="/pics/mousetrap.png"; var mouseholeImg=new Image(); //create new image mouseholeImg.src="/pics/mousehole.jpg"; ///////////////////////////// INITIALIZE variables that change/////////////////////////// function initialize(){ canvas=document.getElementById('canvas'); lifes=3; points=0; cat=new Cat(catImg,50,0, 80,40); //make a Cat(img,x,y,width,height) instance mouse=new Mouse(mouseImg,300,150, 50,50); // Mouse(img,x,y,width,height) treatsArray=[]; // fill treatsArray with Treats for(var i=0;i<8;i++){ // add new Treat with random x,y treatsArray.push(new Treat(Math.floor(Math.random()* canvas.width/30) *30, Math.ceil(Math.random()* (canvas.height-30)/30) *30)); } trapsArray=[]; // fill trapsArray with Traps for(var i=0;i<10;i++){ trapsArray.push(new Trap(Math.floor(Math.random()* (canvas.width-70)/70) *70, Math.ceil(Math.random()* (canvas.height-50)/50) *50)) ; // add new Trap with random x,y if(intersects(trapsArray[trapsArray.length-1],mouse)){ // if trap is under mouse trapsArray[trapsArray.length-1].x=0;} // change x prop } holesArray=[]; // fill holesArray with Holes holesArray.push(new Hole(0,100)) ; // add new HOLE with x,y holesArray.push(new Hole(canvas.width-70,400)) ; // add new HOLE with x,y //........add other instances } ///////////////////////////////////////DRAW WHOLE CANVAS////////////////////////////////////////////////// /// DRAW function draw(){ // draw whole canvas function canvas=document.getElementById('canvas'); context=canvas.getContext('2d'); context.fillStyle='black'; 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<holesArray.length;i++){ holesArray[i].draw(); } cat.draw(); for(var i=0;i<treatsArray.length;i++){ treatsArray[i].draw(); } for(var i=0;i<trapsArray.length;i++){ trapsArray[i].draw(); } // draw these instances mouse.draw(); //......... draw another instance here if(lifes>0){ /// if lefes left:draw lifes context.fillText('LIFES:',5,30) for(var i=0;i<lifes;i++){ /// draw mouse images for each life in top left screen context.drawImage(mouseImg,i*30+100,5,25,25); } animation=setTimeout(draw,100); } else{context.fillText('GAME OVER:',5,30) ;gameover(); } // no lifes: gameover(); } ///////////////////// RESTART ///////////////////////// function stop(){ window.highestTimeoutId = window.setTimeout(";"); /// gets rid of all running timeouts for (var i = 0 ; i < window.highestTimeoutId ; i++) {window.clearTimeout(i); } } 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(); cat.animate(); cat.autoStalk(); } /// ADD TREAT function addTreat(){ // adds a Treat to the Array with random x,y treatsArray.push(new Treat(Math.floor(Math.random()* canvas.width/30) *30, Math.ceil(Math.random()* (canvas.height-30)/30) *30)); } ///ADD POINT function addPoint() { points+=5; } ///RESET function reset(){ cat.justEyes(); cat.x=30;cat.y=30; cat.stop=false; mouse.stop=false; mouse.x=300; mouse.width=50; mouse.height=50; cat.animate(); cat.autoStalk(); } ///GAME OVER function gameover(){ /// clear animations cat.stop=true; mouse.stop=true; clearTimeout(animation);} // DELETE LIFE function deleteLife(){ lifes-=1; // take life off if(lifes<=0){return true;} // if 0 lifes: gameover() else{return false;} } initialize(); draw(); cat.animate(); cat.autoStalk(); </script> <p id="topP"><u>Double click</u> : <b>Start/Restart</b>------- <u>Arrow keys</u> : <b>move mouse</b> -----<u>Enter</u> : <b>run</b> -----<u>Space</u> : <b>eat food</b> and <b>enter hole</b> . <br>Watch out: Cat can hear you and <b>pounces</b> when you eat.</p> <canvas id="canvas" width="500" height="500" tabindex="0" onkeydown="keysFunction()" ondblclick="restart()" onclick="stop()"></canvas> <br><ul> <li>Control mouse with <b>arrow keys</b>(316,321,325,329)</li> <li>Tryout all functions for <b>cat mouse and traps</b>. One by one put them inside the <b>SPACE-key</b> section (309,308,310) of KeysFunction(). Then execute and press SPACE. </li> <li>Decide what should happen inside the <b>SPACE-key</b> (311) to make your game work</li> <li>Add an <b>Enter-section</b> an make it do stuff (enter =13) (332)</li> <li>Change text on top (in p tag) to suit your game (545)</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