1 面向對象編程思想在程序項目中有著非常明顯的優勢:
1- 1 代碼可讀性高.由于繼承的存在,即使改變需求,那么維護也只是在局部模塊
1-2 維護非常方便并且成本較低。
2 這個demo是采用了面向對象的編程思想. 用JavaScript 語言編寫的游戲小程序--貪吃蛇.
代碼注釋詳細,邏輯清晰 . 非常適合新手前端開發者, 鍛煉JavaScript語言的面向對象的編程思想.
該小Demo已上傳GitHub,歡迎下載! 覺得好的話,隨手給個star, 您的star是我最大的動力!
https://github.com/XingJYGo/snakePlay#javascript-經典面向對象demo-貪吃蛇
代碼展示:
代碼結構:
--index.html 地圖頁面,展示蛇和食物,進行游戲
--food.js 構造食物對象
--game.js 構造游戲對象
--snake.js 構造蛇對象
--tool.js 常用數據工具封裝
--index.html 地圖頁面
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>Title</title> <style> #map{ width: 500px; height: 500px; background-color: lightblue; position: relative; } </style></head><body><div id="map"> </div><button id="btn">模擬蛇吃到食物</button><script src="tool.js"></script><script src="food.js"></script><script src="snake.js"></script><script src="game.js"></script><script> ////==========前后方向設定后 ==================var game = new Game();game.start(); </script> </body></html>--food.js 構造食物對象
// 封裝一個食物對象//沙箱模式(function(){ var container; //用于存儲之前的食物 function Food(option) { //防止用戶不傳參數會報錯 option = option || {}; this.width = option.width || 20; this.height = option.height || 20; this.bgc = option.bgc || 'orange'; this.x = option.x || 0; this.y = option.y || 0; this.borderRadius = option.borderRadius |10; } Food.prototype.render = function () { //每一次渲染新的之前就把原來的移除掉 if(container){ map.removeChild(container); } // 創建食物對象 var food = document.createElement('div'); //存到全局變量里 container = food; food.style.width = this.width + 'px'; food.style.height = this.height + 'px'; food.style.backgroundColor = this.bgc; food.style.position = 'absolute'; //獲得隨機位置 //由于要讓食物的位置在每一個格子里面,所有獲取隨機數的算法要重新計算 this.x = Tool.getRandom(0, (map.offsetWidth/ this.width-1)) * this.width; this.y = Tool.getRandom(0, (map.offsetHeight/ this.height-1)) * this.height; food.style.left = this.x + 'px'; food.style.top = this.y + 'px'; food.style.borderRadius = this.borderRadius + 'px'; //渲染上食物 map.appendChild(food); } //因為要在全局使用Food,需要把Food拿到全局中 window.Food = Food;})();
新聞熱點
疑難解答
圖片精選