用java语言写个五子棋的小游戏
时间: 2023-05-31 14:02:39 浏览: 94
Java五子棋小游戏源码
5星 · 资源好评率100%
很抱歉,作为AI语言模型,我无法编写出完整的Java代码。以下是一个简单的五子棋游戏的Java代码示例,供参考:
```java
import java.util.Scanner;
public class FiveInRow {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] board = new int[15][15]; // 棋盘
int currentPlayer = 1; // 当前玩家,1为黑子,2为白子
boolean gameOver = false; // 游戏是否结束
int winner = 0; // 获胜者,1为黑子,2为白子
while (!gameOver) {
// 输出当前棋盘
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
System.out.print(board[i][j] == 0 ? "+" : (board[i][j] == 1 ? "●" : "○") + " ");
}
System.out.println();
}
// 玩家下棋
System.out.println("轮到" + (currentPlayer == 1 ? "黑子" : "白子") + "下棋,请输入坐标(x,y):");
int x = scanner.nextInt();
int y = scanner.nextInt();
if (board[x][y] != 0) { // 如果该位置已经有棋子
System.out.println("该位置已经有棋子,请重新输入坐标。");
continue;
}
board[x][y] = currentPlayer;
// 判断游戏是否结束
boolean win = checkWin(board, x, y);
if (win) {
gameOver = true;
winner = currentPlayer;
} else if (isFull(board)) { // 如果棋盘已满,游戏结束
gameOver = true;
}
// 切换玩家
currentPlayer = currentPlayer == 1 ? 2 : 1;
}
// 输出获胜者
System.out.println(winner == 0 ? "平局!" : (winner == 1 ? "黑子" : "白子") + "获胜!");
}
/**
* 判断棋盘是否已满
*/
private static boolean isFull(int[][] board) {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (board[i][j] == 0) {
return false;
}
}
}
return true;
}
/**
* 判断当前玩家是否获胜
*/
private static boolean checkWin(int[][] board, int x, int y) {
int player = board[x][y];
int count = 0;
// 横向
for (int i = 0; i < 15; i++) {
if (board[x][i] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// 纵向
count = 0;
for (int i = 0; i < 15; i++) {
if (board[i][y] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
// 正斜线
count = 0;
int i = x, j = y;
while (i > 0 && j > 0) {
i--;
j--;
}
while (i < 15 && j < 15) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
i++;
j++;
}
// 反斜线
count = 0;
i = x;
j = y;
while (i > 0 && j < 14) {
i--;
j++;
}
while (i < 15 && j >= 0) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
i++;
j--;
}
return false;
}
}
```
阅读全文