用Java写个五子棋游戏
时间: 2023-03-04 12:13:00 浏览: 101
好的,下面是一份简单的 Java 代码,实现了五子棋游戏:
```
import java.util.Scanner;
public class Wuziqi {
static char[][] board = new char[19][19];
static Scanner scan = new Scanner(System.in);
static boolean flag = true;
public static void main(String[] args) {
initBoard();
while (true) {
showBoard();
System.out.print("请输入您下棋的坐标:");
int x = scan.nextInt();
int y = scan.nextInt();
if (x < 0 || x >= 19 || y < 0 || y >= 19) {
System.out.println("输入坐标不合法,请重新输入!");
continue;
}
if (board[x][y] != '+') {
System.out.println("该位置已经有棋子了,请重新输入!");
continue;
}
if (flag) {
board[x][y] = 'X';
} else {
board[x][y] = 'O';
}
flag = !flag;
if (checkWin(x, y)) {
System.out.println("恭喜,游戏胜利!");
break;
}
}
scan.close();
}
public static void initBoard() {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
board[i][j] = '+';
}
}
}
public static void showBoard() {
System.out.println(" A B C D E F G H I J K L M N O P Q R S");
for (int i = 0; i < 19; i++) {
System.out.print((i + 1) + " ");
for (int j = 0; j < 19; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static boolean checkWin(int x, int y) {
char cur = board[x][y];
int count = 0;
for (int i = x; i >= 0; i--) {
if (board[i][y] != cur) {
break;
}
count++;
}
for (int i = x + 1; i < 19; i++) {
if (board[i][y] != cur) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
count = 0;
阅读全文