js物件導向案例 貪吃蛇

2022-01-29 23:16:26 字數 4694 閱讀 2235

食物物件

1 (function

() ; //

沒有則使用預設值

5this.width = obj.width || 20;

6this.height = obj.height || 20;

7this.top = obj.top || 0;

8this.left = obj.left || 0;

9this.backgroundcolor = obj.backgroundcolor || 'green';

10this.divarr = ;//

儲存$("div")的陣列

11this.map =map;12}

13//

在頁面上用div渲染這個食物

14 food.prototype.render = function

() 23

//隨機生成食物的位置,必須傳入snake物件作為引數

24 food.prototype.random = function

(snake) 36}

37this.left =x;

38this.top =y;

39//

在頁面上改變食物的left,top

40this.divarr[this.divarr.length - 1].css();44}

45 window.food =food;

46 })()

工具物件

1 (function()6

}7 window.tools =tools;

8 })()

snake物件

1 (function

() ; //

沒有則使用預設值

5this.width = obj.width || 20;

6this.height = obj.height || 20;

7this.divarr = ; //

儲存組成蛇的div盒子

8this.map =map;

9this.directioncode = obj.directioncode || 39;

10this.snakenode = [, , ]23}

24//

在頁面上用div渲染蛇

25 snake.prototype.render = function

() 38}39

//根據蛇的方向(directioncode)改變蛇的節點(snakenode)的座標

40//

思路是蛇最後的節點移動到前乙個節點位置,直到蛇頭根據方向移動一格

41//

37 38 39 40 是上下左右的按鍵碼,65 68 83 87 是wasd的鍵碼

42//

需要引數 定時器的標記(在遊戲物件中生成)

43 snake.prototype.move = function

(timgerid)

49//

蛇頭50

switch (this

.directioncode)

78//

獲取地圖的最大座標,如果蛇頭的座標越界則提示遊戲結束

79var maxx = this.map.width() / this

.width;

80var maxy = this.map.height() / this

.height;

81var snakeheadx = this.snakenode[0].left;

82var snakeheady = this.snakenode[0].top;

83if (snakeheadx < 0 || snakeheadx >= maxx || snakeheady < 0 || snakeheady >=maxy)

8788}89

//根據蛇的節點(snakenode)改變儲存在divarr中的div的座標

90//

感覺刪除div 重新生成div 可能會消耗瀏覽器效能

91 snake.prototype.change = function

() )98}

99}100//

snake的eat方法,需要引數 食物物件 定時器的標記

101 snake.prototype.eat = function

(food, timgerid)

113}

114//

當蛇頭與食物座標重合

115if (a &&b) );

125 food.render(); //

重新生成食物

126 food.random(this);//

隨機座標

127}

128}

129 window.snake =snake;

130 })();

遊戲物件

1 (function

() 11

//通過原型新增乙個開始的方法

12 game.prototype.star = function

() 19

20function

kdown() )24}

25//

乙個函式,引數 code 臨時按鍵碼,用來判斷蛇的方向,讓蛇無法掉頭(方向不能直接從上變下)

26function

changingdirectionsuddenly(code)

32if ((that.snake.directioncode === 37 || that.snake.directioncode == 65) && code !== 39 && code !== 68)

35if ((that.snake.directioncode === 38 || that.snake.directioncode == 87) && code !== 40 && code !== 83)

38if ((that.snake.directioncode === 40 || that.snake.directioncode == 83) && code !== 38 && code !== 87) 41}

42return

that.snake.directioncode;43}

44//

蛇移動45

貪吃蛇案例

貪吃蛇大戰 開始暫停 重新整理分數 wrap div1 btn1 btn2 btn3 btn4 建立地圖 var map 01 建立食物 var food 01 建立蛇 var snake 01 var times 0 var speed prompt 請選擇適合自己的速度程度 1,2,3 if s...

貪吃蛇案例

html food.js 食物函式 function window var arr food.prototype.init function map food.prototype.render function map function remove 頭和身體的縱座標是一樣的 把資料放在物件裡,用的...

貪吃蛇 物件導向版

doctype html en utf 8 viewport content width device width,initial scale 1.0 document title map style head grade 0 h2 map div module import game from j...