我目前正在学习使用国际象棋游戏作为项目来处理类(class)。我被女王和国王困住了。 “ReturnMovesList()”函数应该根据对象设置“piece”.moves 数组。我已经为每件作品写了一个剧本。脚本本身应该不重要,但我将其包含在一个案例中。
class Piece {
constructor() {
//not important
}
GetLegalMoves() {
this.SetMoves();
//something else
}
}
class Rook extends Piece{
SetMoves() {
let legal,
rm = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let i in rm) {
let tmp = [];
for (var step = 0; step < this.step; step++){
legal = isLegal(pposChar, pposNum, rm[i][0], rm[i][1]);
if (legal) {
tmp.push(legal);
pposChar += rm[i][0];
pposNum += rm[i][1];
if (isKingAttacked(legal))
tmp.map(n => sqsToBlock.push(n));
} else
break;
}
tmp.map(n => this.moves.push(n));
}
}
}
class Bishop extends Piece {
SetMoves() {
let tmp = [], legal;
for (var i = -1; i <= 1; i += 2) {
for (var j = -1; j <= 1; j += 2) {
tmp = [];
let checkChar = pposChar, checkNum = pposNum;
for (var step = 0; step < this.step; step++) {
legal = isLegal(checkChar, checkNum, i, j);
if (legal) {
tmp.push(legal);
checkChar += i;
checkNum += j;
if (isKingAttacked(legal))
for (var k = 0; k < tmp.length; k++)
sqsToBlock.push(tmp[k]);
} else
break;
}
for (let k = 0; k < tmp.length; k++) {
this.moves.push(tmp[k]);
}
}
}
}
}
class Queen extends ??? {
//need both functions
}
如何让 Queen 对象同时使用这两个功能?也许我做的事情根本就是错误的?
最佳答案
您可以应用其他两个类中的 setMoves 函数:
class Queen extends Piece {
setMoves() {
Bishop.prototype.setMoves.call(this);
Rook.prototype.setMoves.call(this);
}
}
多重继承本身(一个类扩展另外两个类)是不可能的。另一种方法是在 Piece 的不同方法中实现不同的 Action ,或者作为独立函数,然后从 setMoves
实现中调用您需要的 Action 。
这是我实现整个事情的方式:
class Board {
pieces = [];
isValid(x, y) { /*...*/ }
addPiece(piece) {
piece.board = this;
this.pieces.push(piece);
}
}
class Piece {
static moves = [];
validMoves() {
return this.constructor.moves.filter(([x, y]) => this.board.isValid(x, y));
}
}
class Bishop extends Piece {
static moves = [/*...*/];
// no reimplementation of validMoves necessary
}
class Queen extends Piece {
static moves = [...Bishop.moves, /*...*/];
}
关于javascript - 如何使一个对象使用两个不同类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60466022/