首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

《瘋狂 Java 講義》控制台五子棋項目代碼深度分析與流程圖解

     編輯:Java 綜合教學

控制台五子棋完整代碼結構解析

本項目包含三個核心類:Chessboard(棋盤模型)、Chessman(枚舉棋子)、GobangGame(遊戲主邏輯)。

一、Chessboard.java - 棋盤模型

package com.test;
public class Chessboard {
    private String[][] board;
    public static final int BOARD_SIZE = 22;

    public void initBoard() {
        board = new String[BOARD_SIZE][BOARD_SIZE];
        for (int i = 0; i < BOARD_SIZE; i++)
            for (int j = 0; j < BOARD_SIZE; j++)
                board[i][j] = "十";
    }
    public 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 void setBoard(int x, int y, String chessman) { board[x][y] = chessman; }
    public String[][] getBoard() { return board; }
    // test() 方法非核心邏輯,略
}

二、Chessman.java - 枚舉棋子

package com.test;
public enum Chessman {
    BLACK("●"), WHITE("○");
    private String chessman;
    Chessman(String chessman) { this.chessman = chessman; }
    public String getChessman() { return chessman; }
}

三、GobangGame.java - 遊戲主流程

package com.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class GobangGame {
    private final int WIN_COUNT = 5;
    private int posX, posY;
    private Chessboard chessboard;

    public GobangGame(Chessboard chessboard) { this.chessboard = chessboard; }

    // 驗證輸入座標合法性
    public boolean isValid(String inputStr) {
        String[] pos = inputStr.split(",");
        try {
            posX = Integer.parseInt(pos[0]) - 1;
            posY = Integer.parseInt(pos[1]) - 1;
        } catch (NumberFormatException e) { printTip(); return false; }
        if (outOfBounds()) { printTip(); return false; }
        if (!"十".equals(chessboard.getBoard()[posX][posY])) { printTip(); return false; }
        return true;
    }

    // 主遊戲循環
    public void start() throws Exception {
        chessboard.initBoard(); chessboard.printBoard();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        while ((input = br.readLine()) != null) {
            if (!isValid(input)) continue;
            // 玩家落子
            chessboard.setBoard(posX, posY, Chessman.BLACK.getChessman());
            if (isWon(posX, posY, Chessman.BLACK.getChessman())) { if (replay(Chessman.BLACK.getChessman())) continue; break; }
            // 電腦隨機落子
            int[] cp = computerDo();
            chessboard.setBoard(cp[0], cp[1], Chessman.WHITE.getChessman());
            if (isWon(cp[0], cp[1], Chessman.WHITE.getChessman())) { if (replay(Chessman.WHITE.getChessman())) continue; break; }
            chessboard.printBoard(); System.out.println("請輸入座標:");
        }
    }

    // 勝負判定:從最後落子點向四方向檢查連續 5 子
    public boolean isWon(int x, int y, String ico) {
        // 計算檢查範圍 [startX, endX] × [startY, endY]
        int startX = Math.max(0, x - WIN_COUNT + 1);
        int endX = Math.min(BOARD_SIZE - 1, x + WIN_COUNT - 1);
        int startY = Math.max(0, y - WIN_COUNT + 1);
        int endY = Math.min(BOARD_SIZE - 1, y + WIN_COUNT - 1);
        String[][] b = chessboard.getBoard();
        int cnt = 0;
        // 豎向
        for (int i = startY; i < endY; i++)
            if (ico.equals(b[x][i]) && ico.equals(b[x][i+1])) { if (++cnt == WIN_COUNT-1) return true; } else cnt = 0;
        // 橫向
        cnt = 0;
        for (int i = startX; i < endX; i++)
            if (ico.equals(b[i][y]) && ico.equals(b[i+1][y])) { if (++cnt == WIN_COUNT-1) return true; } else cnt = 0;
        // 主對角線
        cnt = 0;
        for (int i = startX, j = startY; i < endX && j < endY; i++, j++)
            if (ico.equals(b[i][j]) && ico.equals(b[i+1][j+1])) { if (++cnt == WIN_COUNT-1) return true; } else cnt = 0;
        return false;
    }

    // 電腦隨機落子
    public int[] computerDo() {
        int x, y;
        String[][] b = chessboard.getBoard();
        do { x = (int)(Math.random()*(BOARD_SIZE-1)); y = (int)(Math.random()*BOARD_SIZE); }
        while (!"十".equals(b[x][y]));
        return new int[]{x, y};
    }

    // 重新開始確認
    public boolean replay(String winner) throws Exception {
        chessboard.printBoard();
        System.out.println((Chessman.BLACK.getChessman().equals(winner)?"你贏":"你輸") + ",再來一盤?(Y/N)");
        return "y".equalsIgnoreCase(new BufferedReader(new InputStreamReader(System.in)).readLine());
    }

    public static void main(String[] args) throws Exception {
        new GobangGame(new Chessboard()).start();
    }
}

四、流程圖解

遊戲流程圖

五、關鍵設計點

  • 枚舉封裝棋子顯示符,類型安全。
  • 勝利判定採用「局部掃描」而非全盤遍歷,性能優。
  • 電腦落子純隨機,無 AI 邏輯,留作擴展點。
  • 控制台交互使用 BufferedReader 讀取標準輸入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved