試玩地址
項目地址
使用方法:
git clonenpm inpm run dev
實現思路如下:
關鍵實現
DOM
<div class="box"> <div class="row" v-for="row in list"> <div class="col" :class="'n-'+col" v-for="col in row">{col}}</div> </div></div>主要的游戲部分的DOM,很簡單,用一個二維數組渲染,并動態綁定樣式
左移
主要由以下幾種情況:
2 2 2 2 => 4 4 0 0 4 2 2 2 => 4 4 2 0 0 4 2 2=> 4 4 0 0 2 2 4 2 => 4 4 2 0按單行數據舉例,
因為一輪移動中,一個數只能合并一次,所以每個格子要有merged參數來記錄是否已經合并過。
主要代碼:
_list.forEach(item => { let farthest = this.farthestPosition(list, item) let next = list[farthest - 1] if (next && next === item.value && !_list[farthest - 1].merged) { //合并 list[farthest - 1] = next * 2 list[item.x] = undefined item = { x: farthest - 1, merged: true, value: next * 2 } this.score += next * 2 } else { if (farthest != item.x) { list[farthest] = item.value list[item.x] = undefined item.x = farthest } } })矩陣旋轉
因為上移,下移,左移,右移實際上是相同的,寫4遍也可以,但是容易出錯,所以我直接旋轉將矩陣旋轉,再進行移動。
以上移為例,只要將矩陣逆時針旋轉一次,上移就變成了左移,移動合并成之后,只要再將矩陣逆時針旋轉4-1次,矩陣就和單純上移一樣了。
逆時針旋轉算法:
rotate(arr, n) { n = n % 4 if (n === 0) return arr let tmp = Array.from(Array(this.size)).map(() => Array(this.size).fill(undefined)) for (let i = 0; i < this.size; i++) { for (let j = 0; j < this.size; j++) { tmp[this.size - 1 - i][j] = arr[j][i] } } if (n > 1) tmp = this.rotate(tmp, n - 1) return tmp },
新聞熱點
疑難解答
圖片精選