exercise - pacman
Transcription
exercise - pacman
SIMPLE MODEL OF THE BROWSER EXERCISE - PACMAN John R. Williams and Abel Sanchez VIDEO PACMAN EXERCISE EXERCISE - PACMAN Copy the two images above and save them as "PacMan1.png" and "PacMan2.png". Copy the code below into a file called PacMan.html. Lets see if we can swap the image PacMan1.png for the image PacMan2.png by changing the "src" of the image. We'll do this first in the Console and then by inputting Javascript in the Web Page. So after loading the html file open the Chrome Development Environment and the Console. Type in the following Now lets write code in 'Run()' to flip-flop between the two images when you click on the image. 1 <html> 2 <head> 3 <SCRIPT> 4 var flag = 1; 5 var img1 = null; 6 function Run(){ 7 img1 = document.getElementById("PacMan"); 8 if(flag === 1){ 9 img1.src = "PacMan2.png"; 10 flag = 0; 11 } 12 else { 13 img1.src = "PacMan1.png"; 14 flag = 1; 15 } 16 } 17 </SCRIPT> 18 </head> 19 <body> 20 <img id="PacMan" src = "PacMan1.png" 21 onclick="Run()" > </img> 22 </body> 23 </html> 24 Make sure you understand why the image changes every time you click on it. Notice that we added onclick="Run()" to the "img" tag. Now lets make the image move across the page every time we click on it. To do this we need to look at what data we can change in the "img" object. The x-coordinate of the image is called "left" and we can get a reference to it at img1.style.left . We also need to modify our "img" tag to add style="position:absolute" . 1 <html> 2 <head> 3 <SCRIPT> 4 var flag = 1; 5 var img1 = null; 6 var pos = 0; 7 function Run(){ 8 img1 = document.getElementById("PacMan"); 9 pos = 20; 10 img1.style.left = pos+"px"; 11 if(flag === 1){ 12 img1.src = "PacMan2.png"; 13 flag=0; 14 } 15 else { 16 img1.src = "PacMan1.png"; 17 flag=1; 18 } 19 } 20 </SCRIPT> 21 </head> 22 <body> 23 <img id="PacMan" src = "PacMan1.png" 24 onclick = "Run()" style="position:absolute"> </img> 25 </body> 26 </html> 27 Here is the code from above running FINAL EXERCISE - HAND THIS ONE IN FOR ACTIVE LEARNING Finally can you make the PacMan move across the page in "10px" increments by using the timer 'setInterval(Run,300)'; This way you won't need to click on the image. When the PacMan goes off the right hand side of the page can you reset the postion back to zero? It should look like the PacMan on the next page. THE END