• 贪吃蛇小游戏(含详细思路及源代码)


    自己写的一个简陋的贪吃蛇游戏,源代码如下:

      1 <!DOCTYPE html>
      2 <html lang="en">
      3 <head>
      4     <meta charset="UTF-8">
      5     <title>贪吃蛇小游戏</title>
      6     <style>
      7 *{margin:0; padding:0;}
      8 header {
      9     display: block;
     10     margin: 0 auto;
     11     width: 500px;
     12     text-align: center;
     13 }
     14 header h1 {
     15     font-family: Arial;
     16     font-weight: bold;
     17 }
     18 header #newGameButton {
     19     display: block;
     20     margin: 20px auto;
     21     width: 100px;
     22     padding: 10px 10px;
     23     background-color: #8f7a66;
     24     font-family: Arial;
     25     color: white;
     26     border-radius: 10px;
     27     text-decoration: none;
     28 }
     29 header #newGameButton:hover {
     30     background-color: #9f8b77;
     31 }
     32 header p {
     33     font-family: Arial;
     34     font-size: 25px;
     35     margin: 20px auto;
     36 }
     37 canvas{
     38     display:block; 
     39     border:medium double black;
     40     margin:4px auto;
     41 }
     42     </style>
     43 </head>
     44 <body>
     45     <header>
     46         <h1>贪吃蛇小游戏</h1>
     47         <a href="javascript:newgame();" id="newGameButton">New Game</a>
     48         <p>score:<span id="score">0</span></p>
     49     </header>
     50     <canvas id="canvas">
     51         Your browser doesn't support the <code>canvas</code> element.
     52     </canvas>
     53     <script>
     54     var CANVAS = document.getElementById("canvas");
     55 var CTX = CANVAS.getContext("2d");
     56 var SNAKE = new Array();    //用队列模拟蛇身
     57 var DIR = "right";                //用来控制蛇头的方向
     58 var SIZE = 20;                //蛇身的宽度
     59 var FOODX = 0;            //食物的x坐标
     60 var FOODY = 0;            //食物的y坐标
     61 var HEADX = 0;        //蛇头的x坐标
     62 var HEADY = 0;        //蛇头的y坐标
     63 var MAXWIDTH = 200;        //画布的高度
     64 var MAXHEIGHT = 200;    //画布的宽度
     65 var TIME = 400;            //蛇的速度
     66 var SCORE = 0;            //计算玩家分数
     67 var interval = null;
     68 
     69 CANVAS.width = MAXWIDTH;
     70 CANVAS.height = MAXHEIGHT;
     71 
     72 window.onload = function(){
     73     newgame();
     74 };
     75 document.getElementById("newGameButton").click(function(){
     76     newgame();
     77 });
     78 function newgame(){
     79     SNAKE = [];        //用队列模拟蛇身
     80     DIR = "right";    //用来控制蛇头的方向
     81     HEADX = 0;        //蛇头的x坐标
     82     HEADY = 0;        //蛇头的y坐标
     83     SCORE = 0;
     84     window.clearInterval(interval);
     85     interval = null;
     86     //初始化画布
     87     CTX.clearRect(0, 0, MAXWIDTH, MAXHEIGHT);
     88     //画一条蛇
     89     drawSnake();
     90     //放置食物
     91     setFood();
     92     //移动蛇
     93     interval = window.setInterval(move, TIME);
     94 
     95 }
     96 function move(){
     97     switch(DIR){
     98         case "up":HEADY = HEADY-SIZE;break;
     99         case "right":HEADX = HEADX+SIZE;break;
    100         case "down":HEADY = HEADY+SIZE;break;
    101         case "left":HEADX = HEADX-SIZE;break;
    102     }
    103     if(HEADX>MAXWIDTH-SIZE || HEADY>MAXHEIGHT-SIZE || HEADX<0 || HEADY<0){
    104         alert("你的分数为:"+SCORE+"分,继续努力吧!失败原因:碰壁了.....");
    105         window.location.reload();
    106     }
    107     for(var i=1;i<SNAKE.length;i++){
    108         if(SNAKE[i][0] == SNAKE[0][0] && SNAKE[i][1] == SNAKE[0][1]){
    109             alert("你的分数为:"+SCORE+"分,继续努力吧!失败原因:撞到自己了.....");
    110             window.location.reload();
    111         }
    112     }
    113     if(SNAKE.length == MAXWIDTH *MAXHEIGHT){
    114         alert("好厉害!么么哒~");
    115         window.location.reload();
    116     }
    117     moveIn(HEADX, HEADY);//移动一格
    118 }
    119 document.onkeydown = function(e) { //改变蛇方向
    120     var code = e.keyCode - 37;
    121     switch(code){
    122         case 1 : DIR = "up";break;//
    123         case 2 : DIR = "right";break;//
    124         case 3 : DIR = "down";break;//
    125         case 0 : DIR = "left";break;//
    126     }
    127 }
    128 //=============================画一条蛇=======================================================
    129 function drawSnake(){
    130     CTX.fillStyle = "black";
    131     //画蛇头
    132     CTX.fillRect (HEADX, HEADY, SIZE, SIZE);
    133     SNAKE.push([HEADX, HEADY]);
    134     
    135     //画蛇身
    136     switch(DIR){
    137         case "up": 
    138             drawBody(HEADX, HEADY + SIZE, HEADX, HEADY + 2 * SIZE);
    139             break;
    140         case "right": 
    141             drawBody(HEADX - SIZE, HEADY, HEADX - 2 * SIZE, HEADY);
    142             break;
    143         case "down": 
    144             drawBody(HEADX, HEADY - SIZE, HEADX, HEADY - 2 * SIZE);
    145             break;
    146         case "left": 
    147             drawBody(HEADX + SIZE, HEADY, HEADX + 2 * SIZE, HEADY);
    148             break;
    149     }
    150 }
    151 function drawBody(x1, y1, x2, y2){
    152     CTX.fillRect (x1, y1, SIZE, SIZE); 
    153     CTX.fillRect (x2, y2, SIZE, SIZE); 
    154     SNAKE.push([x1, y1]);
    155     SNAKE.push([x2, y2]);
    156 }
    157 //===========================放置食物==============================
    158 function setFood(){
    159     do{
    160         FOODX = SIZE * Math.floor(Math.random() * MAXWIDTH / SIZE);
    161         FOODY = SIZE * Math.floor(Math.random() * MAXHEIGHT / SIZE);
    162     }while(foodInSnake());
    163     CTX.fillStyle = "red";
    164     CTX.fillRect (FOODX, FOODY, SIZE, SIZE);
    165 }
    166 function foodInSnake(){
    167     for (var i = 0; i < SNAKE.length; i++) {
    168         if(FOODX == SNAKE[i][0] && FOODY == SNAKE[i][1]){
    169             return true;
    170         }
    171     }
    172     return false;
    173 }
    174 //========================================移动一格===========================
    175 function moveIn(x, y){
    176     CTX.fillStyle = "black";
    177     CTX.fillRect(x, y, SIZE, SIZE);//重画蛇头    
    178     //把新蛇头添加到 SNAKE 数组
    179     var newSnake = [[x, y]];
    180     SNAKE = newSnake.concat(SNAKE);
    181 
    182     if(false == eatFood()){//如果没吃到食物,减少一格蛇尾    
    183         var snakeTail = SNAKE.pop();//获得蛇尾位置
    184         CTX.clearRect(snakeTail[0], snakeTail[1], SIZE, SIZE);//去掉蛇尾    
    185     }
    186 }
    187 function eatFood(){
    188     if(HEADX == FOODX && HEADY == FOODY){
    189         CTX.fillStyle = "block";
    190         CTX.fillRect (FOODX, FOODY, SIZE, SIZE);
    191 
    192         setFood();
    193         SCORE++;
    194         //$("#score").text(SCORE);
    195         document.getElementById("score").innerHTML = SCORE;
    196         return true;
    197     }
    198     return false;
    199 }
    200 
    201     </script>
    202 </html>
    查看代码

    效果图:

    思路:

    function newgame(){
        重置蛇和分数的数据;
        清除interval;
        初始化画布;
        画一条蛇;
        放置食物;
        使用定时器(setInterval)使蛇移动(move函数);
    }
    function move(){
        根据方向改变蛇头下一格将要到达的位置;
        判断游戏是否结束,以及显示结束的原因(包含输赢);
        蛇移动一格(moveIn函数);
    }
    对键盘的方向键作监控,当改变方向时,修改全局变量DIR的值(用于存储方向);
    function moveIn(){
        在蛇头的前一格增加一格作为新的蛇头,并将蛇头的坐标作为第一个元素加入到代表蛇的数组中;
        if(没吃到食物){
            删除一格蛇尾,在画布中做相应改变;
        }
    }

    欢迎各位试玩和纠错~(*^__^*)

     需要注意的是,如果需要在JS中设定canvas中的宽度和高度,和设置其他CSS属性略有不同。CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT; 

  • 相关阅读:
    Cheat Engine 创建线程
    Cheat Engine 人造指针
    Cheat Engine 特征码
    Cheat Engine 自动注入
    Cheat Engine 作弊表框架代码
    Cheat Engine 修改汇编指令
    Shell 选择排序
    Shell 冒泡排序
    Selenium API常用方法
    Selenium数据驱动
  • 原文地址:https://www.cnblogs.com/shy-huiying/p/5387523.html
Copyright © 2020-2023  润新知