<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>游戏初始化界面</title><style>body {margin: 0;padding: 0;}#main {margin: 100px;}.btn {width: 100px;height: 40px;}</style>
</head><body><div id="main"><!-- 按钮 --><input class="btn" type="button" value="开始游戏" id="begin"><input class="btn" type="button" value="暂停游戏" id="pause"></div><!-- 贪吃蛇游戏设计 --><script>var main = document.getElementById('main');/* 画布格子是否开启 */var showcanvas = true;/* atom 原子大小 xnum横向原子数量 ynum纵向原子数量 */function Map(atom, xnum, ynum) {this.atom = atom;this.xnum = xnum;this.ynum = ynum;//声明画布this.canvas = null;//创建画布方法this.create = function() {this.canvas = document.createElement('div');this.canvas.style.cssText = 'position:relative;top:40px;border:1px solid red;background:#FAFAFA';this.canvas.style.width = this.atom * this.xnum + 'px'; //画布的宽this.canvas.style.height = this.atom * this.ynum + 'px'; //画布的宽main.appendChild(this.canvas);if (showcanvas) {for (var x = 0; x < xnum; x++) {for (var y = 0; y < ynum; y++) {var a = document.createElement('div');a.style.cssText = "border:1px solid yellow";a.style.width = this.atom + 'px';a.style.height = this.atom + 'px';a.style.backgroundColor = 'green';this.canvas.appendChild(a);a.style.position = 'absolute';a.style.left = x * this.atom + 'px';a.style.top = y * this.atom + 'px';}}}}}var map = new Map(20, 40, 20);map.create();var timer; //变量可以提升/* 第一部分 *//* 第一部分开始 */document.getElementById('begin').onclick = function() {clearInterval(timer);timer = setInterval(function() {}, 300)}/*第一部分 暂停 */document.getElementById('begin').onclick = function() {clearInterval(timer);timer = setInterval(function() {}, 300)}</script>
</body></html>
运行结果