帮我用java写一个简单的五子棋程序,要求输入棋子的坐标,输出获胜的五个棋子的坐标。棋子的坐标又大写字母和数字组成,行坐标为大写字母A到O,列坐标为数字1到15.不需要打印棋盘,只需实现输入和输出棋子的功能
时间: 2023-12-24 14:03:36 浏览: 22
好的,以下是一个简单的五子棋程序,输入棋子坐标,输出获胜的五个棋子坐标:
```java
import java.util.*;
public class Gobang {
private static final int ROWS = 15;
private static final int COLS = 15;
private static final char[] ROW_LABELS = "ABCDEFGHIJKLMNO".toCharArray();
private static final char EMPTY = '-';
private static final char BLACK = 'X';
private static final char WHITE = 'O';
private char[][] board;
public Gobang() {
board = new char[ROWS][COLS];
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = EMPTY;
}
}
}
public char[][] getBoard() {
return board;
}
public void setBoard(char[][] board) {
this.board = board;
}
public boolean isWin(char color, int row, int col) {
int count = 0;
// 水平方向
for (int j = col - 4; j <= col; j++) {
if (j < 0 || j + 4 >= COLS) continue;
count = 0;
for (int k = j; k <= j + 4; k++) {
if (board[row][k] == color) {
count++;
}
}
if (count == 5) return true;
}
// 垂直方向
for (int i = row - 4; i <= row; i++) {
if (i < 0 || i + 4 >= ROWS) continue;
count = 0;
for (int k = i; k <= i + 4; k++) {
if (board[k][col] == color) {
count++;
}
}
if (count == 5) return true;
}
// 左上到右下方向
for (int i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i < 0 || j < 0 || i + 4 >= ROWS || j + 4 >= COLS) continue;
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] == color) {
count++;
}
}
if (count == 5) return true;
}
// 右上到左下方向
for (int i = row - 4, j = col + 4; i <= row && j >= col; i++, j--) {
if (i < 0 || j >= COLS || i + 4 >= ROWS || j - 4 < 0) continue;
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j - k] == color) {
count++;
}
}
if (count == 5) return true;
}
return false;
}
public void print(char[][] board) {
System.out.print(" ");
for (int j = 0; j < COLS; j++) {
System.out.print(j + 1 + " ");
}
System.out.println();
for (int i = 0; i < ROWS; i++) {
System.out.print(ROW_LABELS[i] + " ");
for (int j = 0; j < COLS; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Gobang gobang = new Gobang();
Scanner scanner = new Scanner(System.in);
char color = BLACK;
while (true) {
gobang.print(gobang.getBoard());
System.out.println("请" + color + "方输入棋子坐标(例如A1):");
String input = scanner.nextLine().trim().toUpperCase();
if (input.length() == 2) {
int row = Arrays.binarySearch(ROW_LABELS, input.charAt(0));
int col = input.charAt(1) - '1';
if (row >= 0 && row < ROWS && col >= 0 && col < COLS && gobang.getBoard()[row][col] == EMPTY) {
gobang.getBoard()[row][col] = color;
if (gobang.isWin(color, row, col)) {
System.out.println(color + "方获胜!");
return;
}
color = color == BLACK ? WHITE : BLACK;
} else {
System.out.println("坐标无效,请重新输入!");
}
} else {
System.out.println("坐标无效,请重新输入!");
}
}
}
}
```
程序运行时,会提示黑色方输入棋子坐标,输入格式为大写字母和数字组成的字符串,如"A1"或"H8",程序会将该位置标记为黑色棋子,并判断是否获胜。如果没有获胜,则提示白色方输入棋子坐标,以此类推。如果某方获胜,则输出该方获胜,并结束程序。