Html5游戏开发之乒乓Ping Pong游戏示例(二)

2019-01-28 19:24:08刘景俊

创建PingPong游戏的元素
我们已经准备就绪,是时候创建PingPong游戏了。

动起来
1、我们将继续我们的jQuery安装示例,在编辑器里打开index.html。
2、然后,在body里用DIV节点创建游戏平台,在游戏平台中有2个拍子和一个球:

复制代码

<divid="game">
<divid="playground">
<divid="paddleA"class="paddle"></div>
<divid="paddleB"class="paddle"></div>
<divid="ball"></div>
</div>
</div>

3、我们现在构建了游戏的对象,现在给他们样式。放置一下代码到head元素中:

复制代码

<style>
#playground{
background:#e0ffe0;
width:400px;
height:200px;
position:relative;
overflow:hidden;
}
#ball{
background:#fbb;
position:absolute;
width:20px;
height:20px;
left:150px;
top:100px;
border-radius:10px;
}
.paddle{
background:#bbf;
left:50px;
top:70px;
position:absolute;
width:30px;
height:70px;
}
#paddleB{
left:320px;
}
</style>

4、在最后的部分,我们将JavaScript逻辑放置到jQuery引用之后。我们将它写到一个单独的文件里,因为我们的代码会越来越大。因此,我们需要创建一个名为html5games.pingpong.js在js文件夹里。
5、我们准备好了JavaScript文件后,需要将他们连接到我们的Html文件。放置以下代码在index.html文件的</body>标签前:

复制代码

<scriptsrc="js/jquery-1.7.min.js"></script>
<scriptsrc="js/html5games.pingpong.js"></script>

[译者友情提示:试试

复制代码

<scriptsrc="js/jquery-1.4.4.js"/>
<scriptsrc="js/html5games.pingpong.js"/>

你会发现按规范写会避免很多麻烦]
6、我们将游戏的逻辑放到html5games.pingpong.js。下面是我们现在唯一的逻辑,初始化球拍:

复制代码

//codeinside$(function(){}willrunaftertheDOMisloadedand
ready
$(function(){
$("#paddleB").css("top","20px");
$("#paddleA").css("top","60px");
});

7、现在让我们在浏览器中测试我们的成果。在浏览器中打开index.html文件我们应该看到先以下截图类似的画面:
 
发生了什么?
在我们的游戏里有了2个球拍和1个球。我们还使用jQuery初始化了2个球拍的位置。