上一节 里沃特与我们分享了《五子飞》的下棋规则,可能有些伙伴看得不清楚,像我们码农还是看到代码比较靠谱。下面就把可以走棋的路线跟大家说一下。
假设从左上角开始,以0开始编号,往右数(没看第一节棋盘的先去看一下)(因为路线比较简单,就直接写固定的数据了):
1.横着走有5条直线:
var lines_h = [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24] ];
2.竖着走也有5条直线:
var lines_v = [ [ 0, 5, 10, 15, 20], [ 1, 6, 11, 16, 21], [ 2, 7, 12, 17, 22], [ 3, 8, 13, 18, 23], [ 4, 9, 14, 19, 24] ];
3.另外还有6条斜线可走:
var lines_o = [ [ 0, 6, 12, 18, 24], [ 4, 8, 12, 16, 20], [ 2, 6, 10], [ 2, 8, 14], [10, 16, 22], [14, 18, 22] ];
合起来即理论下可以走的路线如下:
// 可走的路线 var lines = [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [ 0, 5, 10, 15, 20], [ 1, 6, 11, 16, 21], [ 2, 7, 12, 17, 22], [ 3, 8, 13, 18, 23], [ 4, 9, 14, 19, 24], [ 0, 6, 12, 18, 24], [ 4, 8, 12, 16, 20], [ 2, 6, 10], [ 2, 8, 14], [10, 16, 22], [14, 18, 22] ];
分别用 A,B 表示对战双方:
var Player = { A: 0, B: 1, None: -1 };
棋盘我们直接在 canvas 上画,棋子准备两个小图片:
为棋子定义一个对象:
function Point(x, y, index) { this.x = x; this.y = y; this.index = index; } function Bounds(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; this.toArray = function () { return [this.x, this.y, this.w, this.h]; }; this.toArrayXY = function () { return [this.x, this.y, this.x + this.w, this.y + this.h]; }; } // 棋子 function Chess(player) { this.player = player; this.point = new Point(-1, -1, -1); this.bounds = new Bounds(-1, -1, -1, -1); this.moveTo = function (chess) { chess.player = this.player; this.player = Player.None; }; }
棋盘上棋子定义(棋子初始化):
var i; var cpc = 5; var ctc = Math.pow(cpc, 2); var chesses = []; // 分配棋子 for (i = 0; i < cpc; i++) { chesses[i].player = Player.A; } for (i = cpc; i < ctc - cpc; i++) { chesses[i].player = Player.None; } for (i = ctc - cpc; i < ctc; i++) { chesses[i].player = Player.B; } for (i = 0; i < ctc; i++) { chesses[i].point = new Point(i % cpc, parseInt(i / cpc, 10), i); }
这样,路线和棋子初始化就已经比较清楚了,下一节我们开始在 canvas 上把棋子画好。
时间: 2024-10-12 08:15:02