请用Java编写一个不需要界面并且可以输出胜利棋子的坐标横坐标为数字,纵坐标为大写字母的五子棋程序
时间: 2024-02-15 19:01:40 浏览: 23
以下是一个简单的Java实现:
```java
import java.util.Scanner;
public class FiveChess {
public static void main(String[] args) {
// 初始化棋盘
int[][] board = new int[15][15];
Scanner scanner = new Scanner(System.in);
// 游戏循环
while (true) {
// 读取玩家输入的坐标
System.out.println("请输入您要落子的坐标(例如:C5):");
String input = scanner.nextLine();
int x = input.charAt(0) - 'A';
int y = Integer.parseInt(input.substring(1)) - 1;
// 检查坐标是否合法
if (x < 0 || x >= 15 || y < 0 || y >= 15) {
System.out.println("坐标不合法,请重新输入!");
continue;
}
if (board[x][y] != 0) {
System.out.println("此处已有棋子,请重新输入!");
continue;
}
// 在棋盘上落子
board[x][y] = 1;
// 检查是否胜利
if (checkWin(board, x, y)) {
System.out.println("恭喜你获得胜利!坐标为:" + (char)('A' + x) + (y + 1));
break;
}
}
}
// 检查是否胜利
public static boolean checkWin(int[][] board, int x, int y) {
int player = board[x][y];
int count = 1;
// 检查横向
for (int i = x - 1; i >= 0; i--) {
if (board[i][y] != player) break;
count++;
}
for (int i = x + 1; i < 15; i++) {
if (board[i][y] != player) break;
count++;
}
if (count >= 5) return true;
// 检查纵向
count = 1;
for (int i = y - 1; i >= 0; i--) {
if (board[x][i] != player) break;
count++;
}
for (int i = y + 1; i < 15; i++) {
if (board[x][i] != player) break;
count++;
}
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) break;
count++;
}
for (int i = x + 1, j = y + 1; i < 15 && j < 15; i++, j++) {
if (board[i][j] != player) break;
count++;
}
if (count >= 5) return true;
// 检查左下到右上斜线
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < 15; i--, j++) {
if (board[i][j] != player) break;
count++;
}
for (int i = x + 1, j = y - 1; i < 15 && j >= 0; i++, j--) {
if (board[i][j] != player) break;
count++;
}
if (count >= 5) return true;
return false;
}
}
```
这个程序使用一个二维数组 `board` 来表示棋盘,其中空格为 0,玩家落子为 1,电脑落子为 2。玩家每次输入坐标,程序会检查坐标是否合法,然后在棋盘上落子。每次落子后,程序会检查是否胜利,如果是,则输出胜利信息并结束游戏。如果没有胜利,则继续游戏。