用java写一个五子棋游戏代码
时间: 2024-06-04 08:11:43 浏览: 97
java写的五子棋代码
以下是一个基本的五子棋游戏代码,仅供参考:
import java.util.Scanner;
public class FiveChess {
public static final int ROWS = 15;
public static final int COLS = 15;
public static final int EMPTY = 0;
public static final int BLACK = 1;
public static final int WHITE = 2;
public static int[][] board = new int[ROWS][COLS];
public static int player = BLACK;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
initBoard();
printBoard();
while (true) {
System.out.print("请输入下棋位置(x,y):");
int x = input.nextInt();
int y = input.nextInt();
if (isValidMove(x, y)) {
board[x][y] = player;
printBoard();
if (isWin(x, y)) {
System.out.println((player == BLACK ? "黑" : "白") + "方获胜!");
break;
}
player = (player == BLACK ? WHITE : BLACK);
} else {
System.out.println("下棋位置不合法,请重新输入!");
}
}
}
public static void initBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = EMPTY;
}
}
}
public static void printBoard() {
System.out.print(" ");
for (int i = 0; i < COLS; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < ROWS; i++) {
System.out.print(i + " ");
for (int j = 0; j < COLS; j++) {
if (board[i][j] == EMPTY) {
System.out.print("+ ");
} else if (board[i][j] == BLACK) {
System.out.print("● ");
} else {
System.out.print("○ ");
}
}
System.out.println();
}
}
public static boolean isValidMove(int x, int y) {
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
return false;
}
if (board[x][y] != EMPTY) {
return false;
}
return true;
}
public static boolean isWin(int x, int y) {
int count = 0;
// 横向判断
for (int i = 0; i < COLS; i++) {
if (board[x][i] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 纵向判断
for (int i = 0; i < ROWS; i++) {
if (board[i][y] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 左上到右下斜线判断
for (int i = x, j = y; i >= 0 && i < ROWS && j >= 0 && j < COLS; i--, j--) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
for (int i = x + 1, j = y + 1; i >= 0 && i < ROWS && j >= 0 && j < COLS; i++, j++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 左下到右上斜线判断
for (int i = x, j = y; i >= 0 && i < ROWS && j >= 0 && j < COLS; i--, j++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
for (int i = x + 1, j = y - 1; i >= 0 && i < ROWS && j >= 0 && j < COLS; i++, j--) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
}
阅读全文