{
return ChessConstants.FAIL;
}
setTurnNo(playerNo);
}
ChessPlayer currentPlayer = getCurrentChessPlayer(chessmanType);
currentPlayer.addChessman(new Position(position[0], position[1]));
if (currentPlayer.isWin())
{
reset();
return playerNo == ChessConstants.BLACK ChessConstants.BLACK_WIN
: ChessConstants.WHITE_WIN;
}
return ChessConstants.SUCCESS;
}
private void reset()
{
getPlayer1().clear();
getPlayer2().clear();
setTurnNo(ChessConstants.DEFAULT_TURN);
}
private ChessPlayer getCurrentChessPlayer(ChessmanType chessmanType)
{
if (getPlayer1().getChessmanType() == chessmanType)
{
return getPlayer1();
}
else
{
return getPlayer2();
}
}
/**
* 判断当前棋子是否合法:包括参数不合法、超越棋盘边界、重复落子
*
*/
private boolean isIllegalPosition(int[] position)
{
if (null == position || position.length != 2)
{
return true;
}
Position pos = new Position(position[0], position[1]);
return isIllegalPosition(pos);
}
private boolean isIllegalPosition(Position position)
{
// 越界
if (getChessboard().isOverEdge(position))
{
return true;
}
// 重复落子
if (getPlayer1().contains(position) || getPlayer2().contains(position))
{
return true;
}
return false;
}
private Chessboard getChessboard()
{
return chessboard;
}
private ChessPlayer getPlayer1()
{
return player1;
}
private ChessPlayer getPlayer2()
{
return player2;
}
private int getTurnNo()
{
return turnNo;
}
private void setTurnNo(int turnNo)
{
this.turnNo = turnNo;
}
}
/**
*
* 类名称:ChessGame 类描述: 创建人:dobuy
*
*/
public class ChessGame
{
private Chessboard chessboard;
private ChessPlayer player1;
private ChessPlayer player2;
private int turnNo = ChessConstants.DEFAULT_TURN;
public ChessGame()
{
chessboard = new Chessboard();
player1 = new ChessPlayer(ChessmanType.BLACK);
player2 = new ChessPlayer(ChessmanType.WHITE);
}
/**
* 启动游戏: 每次落一子,如果棋子位置在棋盘上,且落子顺序正常(黑子白子交替下), 则添加棋子到棋盘上,如果没人赢,返回落子成功;
* 如果当前黑子/白子赢了,则返回黑子/白子赢的编号(非棋手的编号)
*
* @param playerNo:玩家序号:黑子棋手/白子棋手
* @param position 落子位置
*
*/
public int startGame(int playerNo, int[] position)
{
ChessmanType chessmanType = ChessmanType.getChessmanTypeByNo(playerNo);
if (ChessmanType.ERROR == chessmanType)
{
return ChessConstants.FAIL;
}
// 位置非法:参数非法、重复落子、棋子位置越界
if (isIllegalPosition(position))
{
return ChessConstants.FAIL;
}
if (getTurnNo() == ChessConstants.DEFAULT_TURN)
{
setTurnNo(chessmanType.getChessmanType());
}
// 不是第一次落子时,判断上一次落子的下一个选手的序号是否和输入相同
else
{
if ((getTurnNo() + 1) % 2 != playerNo)
{
return ChessConstants.FAIL;
}
setTurnNo(playerNo);
}
ChessPlayer currentPlayer = getCurrentChessPlayer(chessmanType);
currentPlayer.addChessman(new Position(position[0], positi