Java编程实现五子棋人人对战代码示例
代码如下:
import java.util.Scanner;
public class Gobang {
private static final int BOARD_SIZE = 15; //棋盘大小
private String[][] board = new String[BOARD_SIZE][BOARD_SIZE]; //棋盘数组
//初始化棋盘,所有格子都用"+"符号表示
public void initBoard() {
for(int i=0; i<BOARD_SIZE; i++) {
for(int j=0; j<BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
}
//在控制台上打印棋盘
public void printBoard() {
for(int i=0; i<BOARD_SIZE; i++) {
for(int j=0; j<BOARD_SIZE; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
//玩家落子的方法
public void playerPutChess(String chess) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入您要落子的位置,格式如:5,5");
String inputStr = scanner.nextLine();
String[] posStrArr = inputStr.split(",");
int posX = Integer.parseInt(posStrArr[0]) - 1;
int posY = Integer.parseInt(posStrArr[1]) - 1;
if(board[posX][posY].equals("+")) {
board[posX][posY] = chess;
}
}
//判断游戏是否结束
public boolean isGameOver(int posX, int posY) {
if(checkRow(posX, posY) || checkCol(posX, posY) || checkDiagonal(posX, posY)) {
return true;
}
return false;
}
//判断一行是否有五子连珠
public boolean checkRow(int posX, int posY) {
String chess = board[posX][posY];
int count = 0;
for(int i=posY-4; i<=posY+4; i++) {
if(i<0 || i>=BOARD_SIZE) {
continue;
}
if(board[posX][i].equals(chess)) {
count++;
} else {
count = 0;
}
if(count == 5) {
return true;
}
}
return false;
}
//判断一列是否有五子连珠
public boolean checkCol(int posX, int posY) {
String chess = board[posX][posY];
int count = 0;
for(int i=posX-4; i<=posX+4; i++) {
if(i<0 || i>=BOARD_SIZE) {
continue;
}
if(board[i][posY].equals(chess)) {
count++;
} else {
count = 0;
}
if(count == 5) {
return true;
}
}
return false;
}
//判断两个对角线是否有五子连珠
public boolean checkDiagonal(int posX, int posY) {
String chess = board[posX][posY];
int count = 0;
for(int i=-4; i<=4; i++) {
if(posX+i < 0 || posX+i >= BOARD_SIZE || posY+i < 0 || posY+i >= BOARD_SIZE) {
continue;
}
if(board[posX+i][posY+i].equals(chess)) {
count++;
} else {
count = 0;
}
if(count == 5) {
return true;
}
}
count = 0;
for(int i=-4; i<=4; i++) {
if(posX+i < 0 || posX+i >= BOARD_SIZE || posY-i < 0 || posY-i >= BOARD_SIZE) {
continue;
}
if(board[posX+i][posY-i].equals(chess)) {
count++;
} else {
count = 0;
}
if(count == 5) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Gobang game = new Gobang();
game.initBoard();
game.printBoard();
boolean isGameOver = false;
String chess = "●"; //默认黑棋先下
while(true) {
game.playerPutChess(chess);
game.printBoard();
if(game.isGameOver()) {
System.out.println("游戏结束," + chess + "方胜利!");
break;
}
if(chess.equals("●")) {
chess = "○";
} else {
chess = "●";
}
}
}
}
