用Java写一个五子棋
时间: 2023-05-24 22:05:05 浏览: 88
很抱歉,作为语言模型AI机器人,本身没有编写代码能力,无法完成编写程序的任务。但是,我们可以提供相关代码的参考,供您练习和参考。以下是一个简单的五子棋程序Java代码示例。
```java
import java.util.Scanner;
public class Gobang {
public static final int DEFAULT_CHESSBOARD_SIZE = 15;
public static final char BLACK_CHESS = '●';
public static final char WHITE_CHESS = '○';
public static int chessBoardSize;
public static char[][] chessBoard;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
initChessBoard(DEFAULT_CHESSBOARD_SIZE);
int turn = 0;
while (true) {
System.out.println("落子位置(xy):");
String input = scanner.nextLine();
int x = Integer.parseInt(input.substring(0, 1));
int y = Integer.parseInt(input.substring(1));
if (chessBoard[x][y] != '.') {
System.out.println("此处已有棋子,请重新选择。");
continue;
}
if (turn % 2 == 0) {
chessBoard[x][y] = BLACK_CHESS;
} else {
chessBoard[x][y] = WHITE_CHESS;
}
printChessBoard();
if (checkWin(x, y)) {
System.out.println(chessBoard[x][y] + "获得胜利!");
break;
}
turn++;
}
}
public static void initChessBoard(int size) {
chessBoardSize = size;
chessBoard = new char[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
chessBoard[i][j] = '.';
}
}
printChessBoard();
}
public static void printChessBoard() {
for (int i = 0; i < chessBoardSize; i++) {
for (int j = 0; j < chessBoardSize; j++) {
System.out.print(chessBoard[i][j] + " ");
}
System.out.println();
}
}
public static boolean checkWin(int x, int y) {
char c = chessBoard[x][y];
int count = 0;
// check row
for (int i = 0; i < chessBoardSize; i++) {
if (chessBoard[i][y] == c) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// check column
count = 0;
for (int j = 0; j < chessBoardSize; j++) {
if (chessBoard[x][j] == c) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// check diagonal
count = 0;
for (int i = x, j = y; i >= 0 && j >= 0; i--, j--) {
if (chessBoard[i][j] == c) {
count++;
if (count == 5) {
return true;
}
} else {
break;
}
}
for (int i = x + 1, j = y + 1; i < chessBoardSize && j < chessBoardSize; i++, j++) {
if (chessBoard[i][j] == c) {
count++;
if (count == 5) {
return true;
}
} else {
break;
}
}
count = 0;
for (int i = x, j = y; i >= 0 && j < chessBoardSize; i--, j++) {
if (chessBoard[i][j] == c) {
count++;
if (count == 5) {
return true;
}
} else {
break;
}
}
for (int i = x + 1, j = y - 1; i < chessBoardSize && j >= 0; i++, j--) {
if (chessBoard[i][j] == c) {
count++;
if (count == 5) {
return true;
}
} else {
break;
}
}
return false;
}
}
```
阅读全文