帮我用java写一个五子棋游戏
时间: 2024-01-04 19:04:32 浏览: 88
好的,下面是一个简单的五子棋游戏的Java代码:
```java
import java.util.Scanner;
public class Gobang {
// 棋盘大小
private static final int ROWS = 15;
private static final int COLS = 15;
// 棋子颜色
private static final int EMPTY = 0; // 空格
private static final int BLACK = 1; // 黑子
private static final int WHITE = 2; // 白子
// 记录棋局状态
private static int[][] board = new int[ROWS][COLS];
// 当前下棋方
private static int player = BLACK;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 初始化棋盘
initBoard();
// 开始下棋
while (true) {
// 打印棋盘
printBoard();
// 提示当前下棋方
String playerStr = (player == BLACK) ? "黑子" : "白子";
System.out.println(playerStr + "请落子(x y):");
// 输入落子位置
int x = scanner.nextInt();
int y = scanner.nextInt();
// 判断落子是否合法
if (x < 0 || x >= ROWS || y < 0 || y >= COLS || board[x][y] != EMPTY) {
System.out.println("落子位置不合法,请重新输入!");
continue;
}
// 落子
board[x][y] = player;
// 判断胜负
if (isWin(player, x, y)) {
System.out.println(playerStr + "获胜!");
break;
}
// 切换下棋方
player = (player == BLACK) ? WHITE : BLACK;
}
scanner.close();
}
// 初始化棋盘
private static void initBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = EMPTY;
}
}
}
// 打印棋盘
private static void printBoard() {
System.out.print(" ");
for (int j = 0; j < COLS; j++) {
System.out.print(j + " ");
}
System.out.println();
for (int i = 0; i < ROWS; i++) {
System.out.print(i + " ");
for (int j = 0; j < COLS; j++) {
if (board[i][j] == EMPTY) {
System.out.print("+ ");
} else if (board[i][j] == BLACK) {
System.out.print("● ");
} else if (board[i][j] == WHITE) {
System.out.print("○ ");
}
}
System.out.println();
}
}
// 判断是否获胜
private static boolean isWin(int player, int x, int y) {
// 判断横向是否连成五子
int count = 1;
for (int i = x - 1; i >= 0; i--) {
if (board[i][y] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1; i < ROWS; i++) {
if (board[i][y] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断纵向是否连成五子
count = 1;
for (int j = y - 1; j >= 0; j--) {
if (board[x][j] == player) {
count++;
} else {
break;
}
}
for (int j = y + 1; j < COLS; j++) {
if (board[x][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断左斜是否连成五子
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y + 1; i < ROWS && j < COLS; i++, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断右斜是否连成五子
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < COLS; i--, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y - 1; i < ROWS && j >= 0; i++, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 没有连成五子
return false;
}
}
```
这个程序实现了一个简单的控制台五子棋游戏,有以下几个功能:
1. 初始化棋盘;
2. 打印棋盘;
3. 提示当前下棋方;
4. 输入落子位置;
5. 判断落子是否合法;
6. 落子;
7. 判断胜负;
8. 切换下棋方。
阅读全文