请用Java代码实现一个五指棋的游戏,棋盘要有线条,通过控制台输入,可以判断游戏的胜利、平局和失败
时间: 2024-05-01 08:20:52 浏览: 119
一个用JAVA实现的五子棋代码
4星 · 用户满意度95%
以下是Java代码实现的五子棋游戏,棋盘使用了ASCII字符画的形式,通过控制台输入棋子的坐标进行下棋,程序会自动判断胜负或平局:
```java
import java.util.Scanner;
public class FiveInARowGame {
private static final int BOARD_SIZE = 15; // 棋盘大小
private static final char[][] board = new char[BOARD_SIZE][BOARD_SIZE]; // 棋盘数组
private static final char BLACK_PIECE = '●'; // 黑子
private static final char WHITE_PIECE = '○'; // 白子
private static final int[][] DIRECTIONS = new int[][]{
{1, 0}, // 右
{0, 1}, // 下
{1, 1}, // 右下
{1, -1} // 右上
};
public static void main(String[] args) {
initBoard(); // 初始化棋盘
printBoard(); // 打印棋盘
Scanner scanner = new Scanner(System.in);
char currentPiece = BLACK_PIECE; // 当前下棋的棋子,默认为黑子
while (true) {
System.out.println("请 " + currentPiece + " 下棋,输入坐标(x,y):");
int x = scanner.nextInt();
int y = scanner.nextInt();
if (isValidMove(x, y)) {
board[x][y] = currentPiece; // 下棋
printBoard(); // 打印棋盘
if (isWin(x, y, currentPiece)) {
System.out.println(currentPiece + " 赢了!");
break;
}
if (isDraw()) {
System.out.println("平局!");
break;
}
currentPiece = (currentPiece == BLACK_PIECE) ? WHITE_PIECE : BLACK_PIECE; // 切换下棋的棋子
} else {
System.out.println("无效的坐标,请重新输入!");
}
}
}
/**
* 初始化棋盘
*/
private static void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '┼'; // 初始值为 '+'
}
}
}
/**
* 打印棋盘
*/
private static void printBoard() {
System.out.print(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((char) ('A' + i) + " ");
}
System.out.println();
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.printf("%2d ", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
/**
* 判断坐标是否有效
*/
private static boolean isValidMove(int x, int y) {
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == '┼';
}
/**
* 判断是否胜利
*/
private static boolean isWin(int x, int y, char currentPiece) {
for (int[] direction : DIRECTIONS) {
int count = 1; // 统计相同颜色的棋子数量
int dx = direction[0], dy = direction[1]; // 方向
// 向左或向上延伸
for (int i = 1; i <= 4; i++) {
int nx = x - i * dx, ny = y - i * dy;
if (nx < 0 || ny < 0 || nx >= BOARD_SIZE || ny >= BOARD_SIZE || board[nx][ny] != currentPiece) {
break;
}
count++;
}
// 向右或向下延伸
for (int i = 1; i <= 4; i++) {
int nx = x + i * dx, ny = y + i * dy;
if (nx < 0 || ny < 0 || nx >= BOARD_SIZE || ny >= BOARD_SIZE || board[nx][ny] != currentPiece) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
}
return false;
}
/**
* 判断是否平局
*/
private static boolean isDraw() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == '┼') {
return false;
}
}
}
return true;
}
}
```
使用控制台输入坐标进行下棋,例如输入 `10 10` 表示在第10行、第10列下棋。棋子颜色轮流为黑子和白子,程序会自动判断胜负或平局。
阅读全文