文西马龙:http://blog.csdn.net/wenximalong/
采用面向对象思想设计超级马里奥游戏人物(示意图)
怎么用通过按键,来控制图片的位置
这个小游戏,用面向对象会很方便,不用面向对象会很麻烦很麻烦,比如以后要讲解的坦克大战的游戏,要是用纯的面向过程或函数式的方式写,那维护起来会非常的麻烦。
游戏分析:
(1)看看如何通过按钮来控制mario的位置
(2)设计相关的对象(Mario x y ...)
Event对象
onclick属性:当用户点击某个对象时调用的事件句柄
素材
mario.css
.gamediv{
width: 500px;
height: 400px;
background-color: pink;
}
/*表格样式*/
.controlcenter{
width: 200px;
height: 200px;
border: 1px solid red;
}
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 1:
//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;
}
}
}
//创建Mario对象
var mario=new Mario();
//全局函数
function marioMove(direct){
switch(direct){
case 1:
mario.move(direct);
break;
case 0:
break;
case 2:
break;
case 3:
break;
}
}
</script>
</head>
<body>
<div class="gamediv">
<img id="mymario" src="mario.jpg" 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="↑↑" οnclick="marioMove(1)" /></td>
<td>**</td>
</tr>
<tr>
<td><input type="button" value="←←" /></td>
<td>**</td>
<td><input type="button" value="→→" /></td>
</tr>
<tr>
<td>**</td>
<td><input type="button" value="↓↓" /></td>
<td>**</td>
</tr>
</table>
</body>
</html>

再要求:
(1)mario碰到边界给一个提示
(2)mario可以去找另外一个物体,比如蘑菇