坦克大战游戏1.0版

   这是坦克大战游戏1.0版,以后会陆陆续续的完成...

   准备素材(itank.jpg):

   

   代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>坦克游戏1.0版</title>

</head>
<body onkeydown="doSomething(event)">
    <div id="field" style="background-color: black;  500px; height: 400px; position: absolute;">
        <div id="tank" style="background-position-y: -40px; background-image: url('itank.jpg');  40px; height: 40px; position: absolute;" ></div>
    </div>
    <script type="text/javascript">
        //用面向对象的方法开发,web版本的坦克大战1.0(可以通过asdw键来控制坦克的走向)
        function MyTank(x, y, direct) {
            this.x = x;//坦克的横坐标
            this.y = y;//坦克的纵坐标
            this.direct = direct;//方向
            this.speed = 5;//速度
            //初始化
            tank.style.left = this.x+"px";
            tank.style.top = this.y+"px";
            tank.style.backgroundPositionY = "0px";
            //event表示按键事件
            this.move = function move(event) {
                //a 表示左 3
                //s 表示下 2
                //d 表示右 1
                //w 表示上 0
                switch(event.keyCode) {
                    case 65:
                        //a 表示左 3
                        this.x -= this.speed;
                        this.direct = 3; //发射子弹的时候要判断方向
                        tank.style.backgroundPositionY = "40px";
                        break;
                    case 83:
                        //s 表示下 2
                        this.y += this.speed;
                        this.direct = 2;
                        tank.style.backgroundPositionY = "80px";
                        break;
                    case 68:
                        //d 表示右 1
                        this.x += this.speed;
                        this.direct = 1;
                        tank.style.backgroundPositionY = "120px";
                        break;
                    case 87:
                         //w 表示上 0
                         this.y -= this.speed;
                         this.direct = 0;
                         tank.style.backgroundPositionY = "0px";
                         break;
                }
                //统一改变位置
                tank.style.left = this.x+"px";
                tank.style.top = this.y+"px";
            }
        }
        //创建坦克
        var hero = new MyTank(300, 360, 0);
        //判断用户希望干什么
        function doSomething(event) {
            if(event.keyCode == 65 || event.keyCode == 68 || event.keyCode == 83 || event.keyCode == 87) {
                hero.move(event);
            } 
            //开火
        }
    </script>
</body>
</html>

   于是坦克就可以在夕阳下狂奔了!!!

原文地址:https://www.cnblogs.com/yerenyuan/p/5398544.html