採用物件導向思想設計超級馬里奧遊戲人物
怎麼用通過按鍵,來控製圖片的位置
這個小遊戲,用物件導向會很方便,不用物件導向會很麻煩很麻煩,比如以後要講解的坦克大戰的遊戲,要是用純的面向過程或函數式的方式寫,那維護起來會非常的麻煩。
遊戲分析:
看看如何通過按鈕來控制mario的位置
設計相關的對象(Mario x y ...)
onclick屬性:當使用者點擊某個對象時調用的事件控制代碼
素材
mario.css
.gamediv{ width: 500px; height: 400px; background-color: pink; } /*表格樣式*/ .controlcenter{ width: 200px; height: 200px; border: 1px solid red; text-align:center;}
mario.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <link rel="stylesheet" type="text/css" href="mario.css" /> <head> <script language="javascript"> //設計Mario類 function Mario(){ this.x=0; this.y=0; //移動 順時針 0->上 1->右 2->下 3->左 this.move=function(direct){ switch(direct){ case 0: //向上//window.alert("mario 右移動"); //這裡為了改變 img的left 和top,我們需要得到 img元素。需要用到javascript的DOM編程。img 對象 var mymario=document.getElementById('mymario'); //取出 img 的top值 //window.alert(mymario.style.top); //怎樣去掉50px的px var top=mymario.style.top; //px佔據兩個,即lenght-2 //window.alert(top.substr(0,top.length-2)); //現在還是串,要轉成數值才能加減 top=parseInt(top.substr(0,top.length-2)); //window.alert(top); mymario.style.top=(top-2)+"px"; //開始移動2px,看怎麼拼接的,字串和數值之間的轉換 //此時mario就可以向下移動了,把上面的列印調試輸出代碼都注釋掉 break; case 1: //向右var mymario=document.getElementById('mymario'); var left=mymario.style.left; left=parseInt(left.substr(0,left.length-2)); mymario.style.left=(left+2)+"px"; break; case 2: //向下var mymario=document.getElementById('mymario'); var top=mymario.style.top; top=parseInt(top.substr(0,top.length-2)); mymario.style.top=(top+2)+"px";break; case 3: //向左var mymario=document.getElementById('mymario'); var left=mymario.style.left; left=parseInt(left.substr(0,left.length-2)); mymario.style.left=(left-2)+"px";break; } } } //建立Mario對象 var mario=new Mario(); //全域函數 function marioMove(direct){ switch(direct){ case 0: //向上mario.move(direct); break; case 1: //向右mario.move(direct); break; case 2: //向下mario.move(direct); break; case 3: //向左mario.move(direct); break; } } </script> </head> <body> <div class="gamediv"> <img id="mymario" src="mario.png" style="left:100px; top:50px; position:absolute;" /> <!--用到了絕對位置--> </div> <table border="1px" class="controlcenter"> <tr > <td colspan="3" >遊戲鍵盤</td> </tr> <tr> <td>**</td> <!-- <td><input type="button" value="向上" onclick="mario.move(0)" /></td> 這樣寫也是可以的--><td><input type="button" value="向上" onclick="marioMove(0)" /></td> <td>**</td> </tr> <tr> <td><input type="button" value="向左" onclick="marioMove(3)"/></td> <td>**</td> <td><input type="button" value="向右" onclick="marioMove(1)"/></td> </tr> <tr> <td>**</td> <td><input type="button" value="向下" onclick="marioMove(2)"/></td> <td>**</td> </tr> </table> </body> </html>
程式基本實現了 向上,向左,向右,向下的要求