贪吃蛇是一款著名的游戏,现在我们可以使用html代码实现贪吃蛇。下面是示例代码。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>贪吃蛇</title> <style> #container { width: 400px; height: 400px; border: 1px solid black; } .snake { width: 10px; height: 10px; background-color: green; position: absolute; top: 0; left: 0; } .food { width: 10px; height: 10px; background-color: red; position: absolute; top: 0; left: 0; } </style> </head> <body> <div id="container"> </div> <script> var container = document.querySelector('#container'); var width = container.offsetWidth; var height = container.offsetHeight; var Snake = function() { this.nodes = []; this.direction = 'right'; this.create(); this.move(); }; Snake.prototype.create = function() { for(var i=0; i<5; i++) { var node = document.createElement('div'); node.className = 'snake'; node.style.top = '0'; node.style.left = (i * 10) + 'px'; this.nodes.push(node); container.appendChild(node); } }; Snake.prototype.move = function() { var self = this; setInterval(function() { var firstNode = self.nodes[0]; var lastNode = self.nodes.pop(); var left = parseInt(firstNode.style.left,10); var top = parseInt(firstNode.style.top,10); if(self.direction === 'right') { left += 10; } else if(self.direction === 'down') { top += 10; } else if(self.direction === 'left') { left -= 10; } else if(self.direction === 'up') { top -= 10; } lastNode.style.left = left + 'px'; lastNode.style.top = top + 'px'; self.nodes.unshift(lastNode); },500); }; var Food = function() { this.node = null; this.create(); }; Food.prototype.create = function() { var node = document.createElement('div'); node.className = 'food'; node.style.top = (Math.floor(Math.random() * height/10) * 10) + 'px'; node.style.left = (Math.floor(Math.random() * width/10) * 10) + 'px'; this.node = node; container.appendChild(node); }; var snake = new Snake(); var food = new Food(); </script> </body> </html>
上述代码实现了一个简单的贪吃蛇游戏。其中,容器div的大小定义了游戏界面的大小,Snake类实现了贪吃蛇的移动和生成,Food类实现了食物的随机生成。通过编写相关的JavaScript代码,可以实现游戏的基本功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。