五子棋java代码 javafx五子棋游戏(13)


String[] posStrArr = inputStr.split(",");
try {
posX = Integer.parseInt(posStrArr[0]) - 1;
posY = Integer.parseInt(posStrArr[1]) - 1;
} catch (NumberFormatException e) {
chessboard.printBoard();
System.out.println("请以(数字,数字)的格式输入:");
return false;
}
// 检查输入数值是否在范围之内
if (posX0 || posX = Chessboard.BOARD_SIZE || posY0
|| posY = Chessboard.BOARD_SIZE) {
chessboard.printBoard();
System.out.println("X与Y坐标只能大于等于1,与小于等于" + Chessboard.BOARD_SIZE
+ ",请重新输入:");
return false;
}
// 检查输入的位置是否已经有棋子
String[][] board = chessboard.getBoard();
if (board[posX][posY] != "十") {
chessboard.printBoard();
System.out.println("此位置已经有棋子,请重新输入:");
return false;
}
return true;
}
/**
* 开始下棋
*/
public void start() throws Exception {
// true为游戏结束
boolean isOver = false;
chessboard.initBoard();
chessboard.printBoard();
// 获取键盘的输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputStr = null;
// br.readLine:每当键盘输入一行内容按回车键,则输入的内容被br读取到
while ((inputStr = br.readLine()) != null) {
isOver = false;
if (!isValid(inputStr)) {
// 如果不合法,要求重新输入 , 再继续
continue;
}
// 把对应的数组元素赋为"●"
String chessman = Chessman.BLACK.getChessman();
chessboard.setBoard(posX, posY, chessman);
// 判断用户是否赢了
if (isWon(posX, posY, chessman)) {
isOver = true;
} else {
// 计算机随机选择位置坐标
int[] computerPosArr = computerDo();
chessman = Chessman.WHITE.getChessman();
chessboard.setBoard(computerPosArr[0], computerPosArr[1],
chessman);
// 判断计算机是否赢了
if (isWon(computerPosArr[0], computerPosArr[1], chessman)) {
isOver = true;
}
}
// 如果产生胜者,询问用户是否继续游戏
if (isOver) {
// 如果继续,重新初始化棋盘,继续游戏
if (isReplay(chessman)) {
chessboard.initBoard();
chessboard.printBoard();
continue;
}
// 如果不继续,退出程序
break;
}
chessboard.printBoard();
System.out.println("请输入您下棋的坐标,应以x,y的格式输入:");
}
}
/**
* 是否重新开始下棋 。
*
* @param chessman
*"●"为用户,"○"为计算机 。
* @return 开始返回true , 反则返回false 。
*/
public boolean isReplay(String chessman) throws Exception {
chessboard.printBoard();
String message = chessman.equals(Chessman.BLACK.getChessman()) ? "恭喜您,您赢了,"
: "很遗憾,您输了,";
System.out.println(message + "再下一局?(y/n)");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if (br.readLine().equals("y")) {
// 开始新一局
return true;
}
return false;
}
/**
* 计算机随机下棋
*/
public int[] computerDo() {
int posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
int posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
String[][] board = chessboard.getBoard();
while (board[posX][posY] != "十") {
posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
}
int[] result = { posX, posY };
return result;
}
/**
* 判断输赢
*
* @param posX
*棋子的X坐标 。

推荐阅读