如何使一个对象使用来自2个不同类的函数?

问题描述 投票:0回答:1

我目前正在使用象棋游戏作为项目来学习与班级合作。而且我坚持皇后和国王。 “ 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对象同时使用这两种功能?也许我在做一些根本错误的事情?

javascript class
1个回答
2
投票

您可以从其他两个类中应用setMoves函数:

class Queen extends Piece {
  setMoves() {
     Bishop.prototype.setMoves.call(this);
     Rook.prototype.setMoves.call(this);
   }
 }

多重继承本身(一个类扩展两个其他类)是不可能的。另一种方法是用不同的Piece方法来实现不同的动作,或者作为独立的函数,然后从setMoves实现中调用所需的动作。

这是我实现整个过程的方法:

 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, /*...*/];
 }
© www.soinside.com 2019 - 2024. All rights reserved.