用java语言写出五子棋的代码
时间: 2023-12-10 15:05:45 浏览: 68
java写的五子棋代码
好的,下面是五子棋的Java代码:
```java
import java.util.Scanner;
public class Gobang {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] board = new int[15][15];
int player = 1;
boolean win = false;
while (!win) {
System.out.println("请输入玩家" + player + "的下棋位置(行 列,以空格隔开):");
int row = sc.nextInt();
int col = sc.nextInt();
if (board[row][col] != 0) {
System.out.println("该位置已经有棋子,请重新输入!");
continue;
}
board[row][col] = player;
printBoard(board);
if (checkWin(board, row, col, player)) {
System.out.println("恭喜玩家" + player + "获胜!");
win = true;
}
player = 3 - player;
}
}
public static boolean checkWin(int[][] board, int row, int col, int player) {
int count = 1;
// 检查行
for (int i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (int i = col + 1; i < 15 && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 检查列
count = 1;
for (int i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (int i = row + 1; i < 15 && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 检查左上到右下的对角线
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (int i = row + 1, j = col + 1; i < 15 && j < 15 && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// 检查左下到右上的对角线
count = 1;
for (int i = row + 1, j = col - 1; i < 15 && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
for (int i = row - 1, j = col + 1; i >= 0 && j < 15 && board[i][j] == player; i--, j++) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
public static void printBoard(int[][] board) {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
```
这个程序实现了一个简单的五子棋游戏,玩家可以输入棋子的位置,程序会检查是否有获胜的情况出现。具体实现可以参考代码中的注释。
阅读全文