java简易五子棋代码
时间: 2023-07-09 07:41:18 浏览: 41
以下是一个简单的 Java 五子棋代码示例:
```java
import java.util.Scanner;
public class Gobang {
private static 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.print("\n");
}
}
public void play() {
Scanner scanner = new Scanner(System.in);
int x = 0, y = 0;
String color = "x";
boolean flag = true;
while (flag) {
System.out.println("请输入您的落子位置,格式为x,y:");
x = scanner.nextInt();
y = scanner.nextInt();
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
System.out.println("落子位置不合法,请重新输入!");
continue;
}
if (!board[x][y].equals("+")) {
System.out.println("该位置已经有子,请重新输入!");
continue;
}
board[x][y] = color;
printBoard();
if (isWin(x, y)) {
flag = false;
System.out.println(color + "方获胜!");
}
color = color.equals("x") ? "o" : "x";
}
scanner.close();
}
public boolean isWin(int x, int y) {
String color = board[x][y];
int count = 1;
// 判断横向
for (int i = y - 1; i >= 0; i--) {
if (board[x][i].equals(color)) {
count++;
} else {
break;
}
}
for (int i = y + 1; i < BOARD_SIZE; i++) {
if (board[x][i].equals(color)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
} else {
count = 1;
}
// 判断纵向
for (int i = x - 1; i >= 0; i--) {
if (board[i][y].equals(color)) {
count++;
} else {
break;
}
}
for (int i = x + 1; i < BOARD_SIZE; i++) {
if (board[i][y].equals(color)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
} else {
count = 1;
}
// 判断左上右下
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j].equals(color)) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
if (board[i][j].equals(color)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
} else {
count = 1;
}
// 判断右上左下
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE; i--, j++) {
if (board[i][j].equals(color)) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0; i++, j--) {
if (board[i][j].equals(color)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Gobang gobang = new Gobang();
gobang.initBoard();
gobang.printBoard();
gobang.play();
}
}
```
该代码实现了一个简单的五子棋游戏,包括棋盘的初始化、输出、落子、判断胜负等功能。其中,isWin()方法用于判断是否获胜,通过遍历每一个方向上的棋子个数来实现。