分享一篇网页贪吃蛇代码



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>贪吃蛇</title>
    <style type="text/css">
    * {
        margin: 0;
        padding: 0;
        font-family: "Microsoft YaHei";
    }
   
    #page {
        margin-right: auto;
        margin-left: auto;
        margin-top: 20px;
        height: 600px;
        width: 980px;
    }
   
    #yard {
        width: 800px;
        border: 1px solid gray;
        box-shadow: 0 0 10px black;
        float: right;
    }
   
    #mark {
        font-weight: 800;
    }
   
    #mark_con {
        color: red;
    }
   
    button {
        width: 50px;
    }
   
    a {
        text-decoration: none;
    }
    </style>
    <script type="text/javascript">
    //伪常量
    var BLOCK_SIZE = 20; //格子大小
    var COLS = 40; //列数
    var ROWS = 30; //行数
    //变量
    var snakes = []; //保存蛇坐标
    var c = null; //绘图对象
    var toGo = 3; //行进方向
    var snakecount = 4; //蛇身数量
    var interval = null; //计时器
    var foodX = 0; //食物X轴坐标
    var foodY = 0; //食物Y轴坐标
    var oMark = null; //分数显示框
    var isPause = false; //是否暂停
    // 绘图函数
    function draw() {
        c.clearRect(0, 0, BLOCK_SIZE * COLS, BLOCK_SIZE * ROWS);
        //画出横线
        for (var i = 1; i <= ROWS; i++) {
            c.beginPath();
            c.moveTo(0, i * BLOCK_SIZE);
            c.lineTo(BLOCK_SIZE * COLS, i * BLOCK_SIZE);
            c.strokeStyle = "gray";
            c.stroke();
        }
        //画出竖线
        for (var i = 1; i <= COLS; i++) {
            c.beginPath();
            c.moveTo(i * BLOCK_SIZE, 0);
            c.lineTo(i * BLOCK_SIZE, BLOCK_SIZE * ROWS);
            c.stroke();
        }
        //画出蛇
        for (var i = 0; i < snakes.length; i++) {
            c.beginPath();
            c.fillStyle = "green";
            c.fillRect(snakes[i].x, snakes[i].y, BLOCK_SIZE, BLOCK_SIZE);
            c.moveTo(snakes[i].x, snakes[i].y);
            c.lineTo(snakes[i].x + BLOCK_SIZE, snakes[i].y);
            c.lineTo(snakes[i].x + BLOCK_SIZE, snakes[i].y + BLOCK_SIZE);
            c.lineTo(snakes[i].x, snakes[i].y + BLOCK_SIZE);
            c.closePath();
            c.strokeStyle = "white";
            c.stroke();
        }
        //画出食物
        c.beginPath();
        c.fillStyle = "yellow";
        c.fillRect(foodX, foodY, BLOCK_SIZE, BLOCK_SIZE);
        c.moveTo(foodX, foodY);
        c.lineTo(foodX + BLOCK_SIZE, foodY);
        c.lineTo(foodX + BLOCK_SIZE, foodY + BLOCK_SIZE);
        c.lineTo(foodX, foodY + BLOCK_SIZE);
        c.closePath();
        c.strokeStyle = "red";
        c.stroke();
    }
    //游戏初始化
    function start() {
        for (var i = 0; i < snakecount; i++) {
            snakes[i] = {
                x: i * BLOCK_SIZE,
                y: 0
            };
        }
        addFood();
        draw();
        oMark.innerHTML = 0;
    }
    //移动函数
    function move() {
        switch (toGo) {
            case 1: //左边
                snakes.push({
                    x: snakes[snakecount - 1].x - BLOCK_SIZE,
                    y: snakes[snakecount - 1].y
                });
                break;
            case 2: //上边
                snakes.push({
                    x: snakes[snakecount - 1].x,
                    y: snakes[snakecount - 1].y - BLOCK_SIZE
                });
                break;
            case 3: //右边
                snakes.push({
                    x: snakes[snakecount - 1].x + BLOCK_SIZE,
                    y: snakes[snakecount - 1].y
                });
                break;
            case 4: //下边
                snakes.push({
                    x: snakes[snakecount - 1].x,
                    y: snakes[snakecount - 1].y + BLOCK_SIZE
                });
                break;
            default:
                ;
        }
        snakes.shift();
        isEat();
        isDie();
        draw();
    }
    //吃到食物判断
    function isEat() {
        if (snakes[snakecount - 1].x == foodX && snakes[snakecount - 1].y == foodY) {
            oMark.innerHTML = (parseInt(oMark.innerHTML) + 1).toString();
            addFood();
            addSnake();
        }
    }
    //添加蛇身
    function addSnake() {
        snakecount++;
        snakes.unshift({
            x: BLOCK_SIZE * COLS,
            y: BLOCK_SIZE * ROWS
        });
    }
    //交互响应函数
    function keydown(keyCode) {
        switch (keyCode) {
            case 37: //左边
                if (toGo != 1 && toGo != 3) toGo = 1;
                break;
            case 38: //上边
                if (toGo != 2 && toGo != 4) toGo = 2;
                break;
            case 39: //右边
                if (toGo != 3 && toGo != 1) toGo = 3;
                break;
            case 40: //下的
                if (toGo != 4 && toGo != 2) toGo = 4;
                break;
            case 80: //开始/暂停
                if (isPause) {
                    interval = setInterval(move, 100);
                    isPause = false;
                    document.getElementById('pause').innerHTML = "Pause";
                } else {
                    clearInterval(interval);
                    isPause = true;
                    document.getElementById('pause').innerHTML = "Start";
                }
                break;
        }
    }
    //制造食物
    function addFood() {
        foodX = Math.floor(Math.random() * (COLS - 1)) * BLOCK_SIZE;
        foodY = Math.floor(Math.random() * (ROWS - 1)) * BLOCK_SIZE;
        // console.log(foodX + " -- " + foodY);
    }
    //死亡判断
    function isDie() {
        if (snakes[snakecount - 1].x == -20 || snakes[snakecount - 1].x == BLOCK_SIZE * COLS || snakes[snakecount - 1].y == -20 || snakes[snakecount - 1].y == BLOCK_SIZE * ROWS) {
            alert("Game Over!");
            clearInterval(interval);
        }
        for (var i = 0; i < snakecount - 1; i++) {
            if (snakes[snakecount - 1].x == snakes[i].x && snakes[snakecount - 1].y == snakes[i].y) {
                clearInterval(interval);
                alert("Game Over!");
            }
        }
    }
    // 启动函数
    window.onload = function() {
        c = document.getElementById('canvas').getContext('2d');
        oMark = document.getElementById('mark_con');
        start();
        interval = setInterval(move, 100);
        document.onkeydown = function(event) {
            var event = event || window.event;
            keydown(event.keyCode);
        }
    }
    </script>
</head>

<body>
    <div id="page">
        <div id="yard">
            <canvas id="canvas" height="600px" width="800px"></canvas>
        </div>
        <div id="help">
            <div id="mark">得分:<span id="mark_con"></span></div>
            <div id="helper">
                <table>
                    <tr>
                        <td></td>
                        <td>
                            <button οnclick="keydown(38);">上</button>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>
                            <button οnclick="keydown(37);">左</button>
                        </td>
                        <td>
                            <button οnclick="keydown(80);" id="pause">暂停</button>
                        </td>
                        <td>
                            <button οnclick="keydown(39);">右</button>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <button οnclick="keydown(40);">下</button>
                        </td>
                        <td></td>
                    </tr>
                </table><a href="index.html">再玩一次</a>
            </div>
        </div>
    </div>
    <div style="text-align:center;">
    </div>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的贪吃蛇网页代码: ```html <!DOCTYPE html> <html> <head> <title>贪吃蛇游戏</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="canvas" width="400" height="400"></canvas> <script> // 初始化画布和上下文 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // 定义贪吃蛇的属性 var snake = { x: 10, y: 10, dx: 10, dy: 0, cells: [], maxCells: 4 }; // 定义食物的属性 var food = { x: Math.floor(Math.random() * 39) * 10, y: Math.floor(Math.random() * 39) * 10 }; // 定义游戏循环 function loop() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 移动贪吃蛇 snake.x += snake.dx; snake.y += snake.dy; // 检查是否撞墙 if (snake.x < 0 || snake.x >= canvas.width || snake.y < 0 || snake.y >= canvas.height) { alert("游戏结束!"); return; } // 添加新的身体部分 snake.cells.unshift({x: snake.x, y: snake.y}); // 删除多余的身体部分 if (snake.cells.length > snake.maxCells) { snake.cells.pop(); } // 绘制贪吃蛇 ctx.fillStyle = "green"; snake.cells.forEach(function(cell, index) { ctx.fillRect(cell.x, cell.y, 10, 10); }); // 绘制食物 ctx.fillStyle = "red"; ctx.fillRect(food.x, food.y, 10, 10); // 检查是否吃到食物 if (snake.x === food.x && snake.y === food.y) { snake.maxCells++; food.x = Math.floor(Math.random() * 39) * 10; food.y = Math.floor(Math.random() * 39) * 10; } // 设置下一帧 requestAnimationFrame(loop); } // 监听键盘事件 document.addEventListener("keydown", function(event) { switch (event.keyCode) { case 37: // 左箭头 snake.dx = -10; snake.dy = 0; break; case 38: // 上箭头 snake.dx = 0; snake.dy = -10; break; case 39: // 右箭头 snake.dx = 10; snake.dy = 0; break; case 40: // 下箭头 snake.dx = 0; snake.dy = 10; break; } }); // 开始游戏循环 requestAnimationFrame(loop); </script> </body> </html> ``` 希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值