javascript开发的贪吃蛇小游戏(纯js代码)

<!Document html>
<html lang="=en">
<head>
	<meta charset='utf-8'>
	<title>贪吃蛇</title>
	<style type="text/css">
		*{
			padding: 0;
			margin: 0;
		}
		.title{
			text-align: center;
			margin: 10px 0;
		}
		#main{
			width: 800px;
			height: 400px;
			border: 1px solid red;
			margin: 0 auto;
		}
		#main .left{
			width: 600px;
			height: 400px;
			float: left;
			position: relative;
		}/*随机的事物通过position定位了*/
		#main .right{
			width: 200px;
			height: 100%;
			float: left;
			border-left: 1px solid red;
			box-sizing: border-box;
			text-align: center;
		}
		#main .right h2{
			margin: 10px auto;
			text-align: center;
		}
		#main .right h2 #score{
			color: red;
		}
		#main .right button{
			width: 100px;
			height: 30px;
			font-size: 20px;
			margin-top: 30px;
			border: 0;
			border-radius: 5px;
			background-color: pink;
			color: green;
		}
		.food{
			background-color: black;
		}
		.snake{
			background-color: darkgreen;
		}
	</style>
</head>
<body>
	<h2 class="title">贪吃蛇</h2>
	<div id="main">
		<div class="left"></div>
		<div class="right">
			<h2 class="status">请点击开始</h2>
			<h2>分数:<span id="score">0</span></h2>
			<button id='btn'>开始</button>
		</div>
	</div>
</body>
<script type="text/javascript">
	 // 设置自定义的游戏参数
    var snake_length = 3; // 正整数,增加额外的蛇身体。0就是最小的3段,1就是额外增加1段。
    var wall_snake = true;  // 开启撞击蛇身
    var wall = true;  // 开启撞墙
    // 获取变量
    var map = document.getElementsByClassName('left')[0];
    var status = document.getElementsByClassName('status');
    var scoreBox = document.getElementById('score');
    var btn = document.getElementById('btn');
    // 初始化
    init();
    // 初始化方法
	 function init() {
        // 获取地图的跨度和高度
        this.map_width = parseInt(getComputedStyle(map).width);
        this.map_height = parseInt(getComputedStyle(map).height);

        // 初始化成绩和界面
        this.score = 0;
        scoreBox.innerHTML = this.score;
        btn.innerHTML = "开始";

        // 食物的高度和宽度
        this.food_width = 20;
        this.food_height = 20;
        // 食物的位置,先定义在左上角看看样子,之后再搞随机位置
        // this.food_X = 0;
        // this.food_Y = 0;
        food();  // 生成食物

        // 初始化蛇身
        this.snake_width = 20;
        this.snake_height = 20;
        // 下面是一个3段的蛇,第一个参数是水平位置,第二个参数是垂直位置,但三个参数是是否是头部
        // 最后发现第三个参数并没有用
        this.snake_body = [[2, 0, true], [1, 0, false], [0, 0, false]];
        // 追加额外的蛇身
        if (typeof snake_length === 'number' && snake_length%1 === 0) {
            // 综合上面的2个条件,可以判断snake_length是一个整数
            for (var i=0; i<snake_length; i++) {
                this.snake_body.push([0, 0, false]);
            }
        }
        // 蛇移动的方向
        this.direction = 'right';
        snake(); // 生成蛇身
    }

    // 点击按钮
    btn.onclick = function () {
        if (this.innerHTML==="开始"){
            start_game();
            this.innerHTML = "暂停";
        } else {
            pause_game();
            this.innerHTML = "开始";
        }
    };

    // 开始游戏
    function start_game() {
        status.innerHTML = "游戏运行中";
        this.snakeMove = setInterval(move, 100);
        // 绑定键盘按下的事件
        bindKeyDown();
    }

    // 键盘按下的事件
    function bindKeyDown() {
        window.onkeydown = function (ev) {
            // status.innerHTML = ev.keyCode;
            var code = ev.keyCode;  // 获取按键
            switch (code){
                case 37:
                    if (this.direction === 'up' ||  this.direction === 'down') {
                        this.direction = 'left';
                    }
                    break;
                case 38:
                    if (this.direction === 'left' ||  this.direction === 'right'){
                        this.direction = 'up';
                    }
                    break;
                case 39:
                    if (this.direction === 'up' ||  this.direction === 'down'){
                        this.direction = 'right';
                    }
                    break;
                case 40:
                    if (this.direction === 'left' ||  this.direction === 'right'){
                        this.direction = 'down';
                    }
                    break;
                case 32:
                    // 我这里还希望开始游戏后,可以用空格控制暂停和开始
                    btn();  // 前面的按钮事件没写
                    break;
            }
        }
    }

	
    // 生成蛇身
    function snake() {
        // 用for循环遍历数组,将每一段作为一个div然后添加
        for(var i=0; i<this.snake_body.length; i++){
            // 创建蛇身
            var snakeBox = document.createElement('div');
            // 高度和宽度
            snakeBox.style.width = this.snake_width+"px";
            snakeBox.style.height = this.snake_height+"px";
            // 定位
            snakeBox.style.position = 'absolute';
            // 位置
            snakeBox.style.top = this.snake_body[i][1]*this.snake_width+"px";
            snakeBox.style.left = this.snake_body[i][0]*this.snake_height+"px";
            // 设置一个类名,然后css给这个类定义样式
            snakeBox.className = "snake";
            // 追加到map中
            map.appendChild(snakeBox);
        }
    }

    // 生成食物
    function food() {
        // 创建食物
        var foodBox = document.createElement('div');
        foodBox.style.width = this.food_width+"px";
        foodBox.style.height = this.food_height+"px";
        // 食物的位置
        this.food_X = Math.floor(Math.random()*this.map_width/this.food_width);  // 0~29之间
        this.food_Y = Math.floor(Math.random()*this.map_height/this.food_height);
        foodBox.style.position = 'absolute';
        foodBox.style.top = this.food_Y*this.food_height+"px";  // 随机数乘以宽度
        foodBox.style.left = this.food_X*this.food_width+"px";
        // 设置一个类名,然后css给这个类定义样式
        foodBox.className = "food";
        // 将食物追加到map中
        map.appendChild(foodBox);
    }
	    // 蛇移动的方法
    function move() {
        // 从尾端开始,数组里的后一个值用数组的前一个值替代
        for(var i=this.snake_body.length-1; i>0; i--){
            this.snake_body[i][0] = this.snake_body[i-1][0];
            this.snake_body[i][1] = this.snake_body[i-1][1];
        }

        // 根据方法来操作
        switch (this.direction){
            case 'left':
                this.snake_body[0][0] -= 1;
                break;
            case 'right':
                this.snake_body[0][0] += 1;
                break;
            case 'up':
                this.snake_body[0][1] -= 1;
                break;
            case 'down':
                this.snake_body[0][1] += 1;
                break;
        }
        // 数组最前的那个值,就是蛇头
        // this.snake_body[0][0] += 1;
        // 判断蛇头吃食物
        if (this.snake_body[0][0]===this.food_X && this.snake_body[0][1]===this.food_Y){
            // status.innerHTML = "吃到食物了"
            clearBox("food");  // 移除食物
            food();  // 生成新的食物
            // 增加分数,先把下面这句加到最上面的获取变量里
            // var scoreBox = document.getElementById('score');
            // 在去初始化函数init()里,加一条初始化分数变量
            // this.score = 0;
            this.score += 1;
            scoreBox.innerHTML = this.score;
            // 增加蛇身长度
            // var snake_end = this.snake_body[this.snake_body.length-1];  // 这个是错误的
            var snake_end = Array.from(this.snake_body[this.snake_body.length-1]);  // 这里需要深copy
            this.snake_body.push(snake_end);
        }

        // 判断撞墙
        wall && (
            this.snake_body[0][0]<0 || this.snake_body[0][0]>=this.map_width/this.snake_width ||
            this.snake_body[0][1]<0 || this.snake_body[0][1]>=this.map_height/this.snake_height
        ) && game_over();

        // 判断撞到蛇身
        if (wall_snake) {
            for (var i=1; i<this.snake_body.length; i++) {
                this.snake_body[i][0] === this.snake_body[0][0] &&
                this.snake_body[i][1] === this.snake_body[0][1] &&
                game_over();
            }
        }

        // 重新生成蛇,才能在页面上有变化
        // 先移除原有的蛇身体
        clearBox('snake');  // 这个方法可以复用,只有要清除食物的时候也能用到
        // 然后绘制新的蛇身
        snake();
    }
	    // 游戏结束的方法
    function game_over() {
        status.innerHTML = "Game Over";
        clearInterval(this.snakeMove);
        alert("游戏结束\n分数:"+this.score);
        clearBox('snake');
        clearBox('food');
        init();
    }

    // 清除Box
    function clearBox(class_name) {
        var box = document.getElementsByClassName(class_name);
        while(box.length){
            map.removeChild(box[0]);
        }
    }

    // 暂停游戏
    function pause_game() {
        // 暂停游戏就是清除定时器
        status.innerHTML = "游戏暂停...";
        clearInterval(this.snakeMove);
    }
</script>
</html>
发布了32 篇原创文章 · 获赞 28 · 访问量 1374

猜你喜欢

转载自blog.csdn.net/Maqiuqiu520/article/details/104443300