这是一个用Java写的五子棋游戏的简单示例代码:
这个代码实现了一个简单的五子棋游戏,可以在控制台中进行游戏。
package com.zhang;
import java.util.Scanner;
public class Test1 {
public static final int BOARD_SIZE = 15;
public static final char EMPTY = '·';
public static final char BLACK = '●';
public static final char WHITE = '○';
private char[][] board;
private char currentPlayer;
public Test1() {
board = new char[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
currentPlayer = BLACK;
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (true) {
printBoard();
System.out.println("轮到 " + currentPlayer + " 下棋");
System.out.print("请输入行号: ");
int row = scanner.nextInt();
System.out.print("请输入列号: ");
int col = scanner.nextInt();
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE || board[row][col] != EMPTY) {
System.out.println("无效的输入,请重新输入");
continue;
}
board[row][col] = currentPlayer;
if (hasWon(row, col)) {
printBoard();
System.out.println(currentPlayer + " 获胜!");
break;
}
currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK;
}
scanner.close();
}
private boolean hasWon(int row, int col) {
return hasWonInDirection(row, col, -1, -1) || hasWonInDirection(row, col, -1, 0)
|| hasWonInDirection(row, col, -1, 1) || hasWonInDirection(row, col, 0, -1)
|| hasWonInDirection(row, col, 0, 1) || hasWonInDirection(row, col, 1, -1)
|| hasWonInDirection(row, col, 1, 0) || hasWonInDirection(row, col, 1, 1);
}
private boolean hasWonInDirection(int row, int col, int rowIncrement, int colIncrement) {
int count = 0;
for (int i = row + rowIncrement * 4, j = col + colIncrement * 4; i != row - rowIncrement
&& j != col - colIncrement; i -= rowIncrement, j -= colIncrement) {
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE || board[i][j] != currentPlayer) {
break;
}
count++;
}
return count >= 5;
}
private void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
new Test1().play();
}
}