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

程式開發流程實戰:從偽代碼到測試驅動的 DotCom 遊戲實作

     編輯:Java 綜合教學

程式開發流程實戰:從偽代碼到測試驅動的 DotCom 遊戲實作

一、建議的開發步驟

  1. 偽代碼:邏輯梳理,不拘語法
  2. 測試代碼:先寫測試定義行為(TDD 思想)
  3. 目標代碼:實作使測試通過

優勢:明確需求、重構安全、單元測試天然形成。

二、DotCom 遊戲需求簡化

  • 一維 7 格陣列,單艘「達康」佔 3 連續格
  • 玩家輸入索引猜測,回傳 "miss"/"hit"/"kill"

三、核心類設計

public class SimpleDotCom {
    private int[] locationCells; // 佔用格位
    private int numOfHits = 0;   // 命中計數

    public void setLocationCells(int[] cells) { this.locationCells = cells; }

    public String checkYourself(int userGuess) {
        String result = "miss";
        for (int cell : locationCells) {
            if (cell == userGuess) {
                result = "hit";
                numOfHits++;
                break;
            }
        }
        if (numOfHits == 3) result = "kill";
        return result;
    }
}

四、測試優先示範

public class Test {
    public static void main(String[] args) {
        SimpleDotCom dotCom = new SimpleDotCom();
        dotCom.setLocationCells(new int[]{2, 3, 4});
        
        System.out.println(dotCom.checkYourself(2)); // hit
        System.out.println(dotCom.checkYourself(3)); // hit
        System.out.println(dotCom.checkYourself(4)); // kill
    }
}

五、細節補充:負數取模陷阱


// Java 中 -3 % 2 == -1,不可用 num % 2 == 1 判斷奇數
// 正確寫法:
num % 2 == 0        // 偶數
num % 2 != 0        // 奇數
Math.abs(num) % 2 == 1 // 亦可

Python 中 -3 % 2 == 1,語言特性不同需注意。

六、後續改進方向

  • 隨機產生位置
  • 多艘船支援
  • 遊戲循環與輸入驗證
  • 圖形介面(Swing/JavaFX)

「偽代碼 → 測試 → 實作」流程讓邏輯清晰、品質可控,值得養成習慣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved