1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>贪吃蛇</title>
    8. <style>
    9. *{
    10. padding: 0;
    11. margin: 0;
    12. box-sizing: border-box;
    13. }
    14. #main{
    15. margin: 100px;
    16. }
    17. .btn{
    18. width: 100px;
    19. height: 40px;
    20. /* margin: 10px; */
    21. }
    22. .canvas{
    23. position: relative;
    24. top: 40px;
    25. border: 1px solid rgb(107, 221, 178);
    26. background-color: rgb(218, 236, 245);
    27. }
    28. </style>
    29. </head>
    30. <body>
    31. <div id="main">
    32. <input class="btn" type="button" value="开始游戏" id="begin"/>
    33. <input class="btn" type="button" value="暂停游戏" id="pause"/>
    34. <script>
    35. var timer; //变量可以提升
    36. var showCanvas = true; //是否显示格子
    37. /*设置地图的构造方法:
    38. atom为原子初始化的宽高(应该一致)
    39. xnum为地图x轴应该有多少个原子(横向)
    40. ynum为地图y轴应该有多少个原子(纵向)
    41. */
    42. function Map(atom,xnum,ynum){
    43. this.atom = atom;
    44. this.xnum = xnum;
    45. this.ynum = ynum;
    46. this.canvas = null; //初始化画布
    47. this.create = function(){
    48. this.canvas = document.createElement("div");
    49. this.canvas.className = "canvas";
    50. this.canvas.style.width = this.atom * this.xnum + "px"; //画布的宽
    51. this.canvas.style.height = this.atom * this.ynum + "px"; //画布的高
    52. main.appendChild(this.canvas);
    53. if (showCanvas){
    54. for (var i = 0;i<xnum;i++){
    55. for (var j = 0;j<ynum;j++){
    56. //定义格子的样式
    57. var lattice = document.createElement("div");
    58. lattice.style.border = "1px solid rgb(107, 221, 178)";
    59. lattice.style.width = this.atom + "px";
    60. lattice.style.height = this.atom + "px";
    61. //添加格子到地图中
    62. this.canvas.appendChild(lattice);
    63. lattice.style.position = "absolute";
    64. //利用绝对定位
    65. lattice.style.left = i * this.atom + "px";
    66. lattice.style.top = j * this.atom + "px";
    67. }
    68. }
    69. }
    70. }
    71. }
    72. //实例化地图类
    73. var map = new Map(20,40,20);
    74. map.create();
    75. //给开始按钮绑定函数
    76. document.querySelector("#begin").onclick = function(){
    77. clearInterval(timer);
    78. timer = setInterval(function(){
    79. },300);
    80. }
    81. document.querySelector("#pause").onclick = function(){
    82. clearInterval(timer);
    83. }
    84. </script>
    85. </div>
    86. </body>
    87. </html>