首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 開發智慧型手機推箱子遊戲 (七) - Step 結構與步驟編碼

     編輯:關於C#

系列回顧

本系列前六篇已介紹專案架構、公用工具類、尋路演算法、基本格子定義。本文聚焦 Common/Step.cs,解析「走法步驟」結構如何支援移動記錄、撤銷/重做、通關錄影回放三大核心功能。

核心定義

namespace Skyiv.Ben.PushBox.Common
{
    // 方向枚舉:無、東、南、西、北
    enum Direction { None, East, South, West, North }

    // 設計模式動作:無、建立、編輯、刪除
    public enum Action { None, Create, Edit, Delete }

    /// 單一走法步驟
    struct Step
    {
        Direction direct;   // 前進方向
        bool isBox;         // 是否推著箱子
        bool isStop;        // 「撤銷」時是否停留在此步驟

        public Direction Direct => direct;
        public bool IsBox => isBox;
        public bool IsStop => isStop;

        public Step(Direction direct, bool isBox, bool isStop)
        {
            this.direct = direct;
            this.isBox = isBox;
            this.isStop = isStop;
        }

        // ── 隱式轉換:Step ⇄ char ──
        // 編碼表:
        //  0-4  : A B C D E  (方向 None~North, 無箱子、非停留)
        //  5-9  : F G H I J  (同方向,有箱子)
        // 10-14 : K L M N O  (同方向,無箱子、停留)
        // 15-19 : P Q R S T  (同方向,有箱子、停留)
        public static implicit operator char(Step step)
        {
            char c = "ABCDE"[step.direct - Direction.None];
            if (step.isBox) c += 5;
            if (step.isStop) c += 10;
            return c;
        }

        public static implicit operator Step(char c)
        {
            int n = c - 'A';
            return new Step(
                (Direction)(n % 5),
                (n % 10 >= 5),
                (n >= 10)
            );
        }
    }
}

設計意圖解析

1. 三元組資訊完整描述一步

欄位含義用途
Direct移動方向重播/撤銷時決定位移向量
IsBox是否推箱撤銷時箱子需跟隨退回
IsStop撤銷停靠點「撤銷」鍵一次退回至最近的 true 步驟

2. 實戰情境演示

假設工人從紅圈走到綠圈推箱子(圖示略),共產生 6 個 Step 實例壓入堆疊:

步驟DirectIsBoxIsStopChar
1WestfalsetrueN
2SouthfalsefalseC
3WestfalsetrueN
4WesttruefalseI
5WesttruefalseI
6WesttruefalseI
  • 點擊「後退」:彈出步驟 6,工人+箱子同向後退一格。
  • 點擊「撤銷」:連續彈出步驟 5、4、3(含推箱退回),停在步驟 3 的 IsStop=true 處(紅圈位置)。
  • 再次「撤銷」:再退步驟 2、1,回到初始位置。

3. Char 編碼:極致壓縮儲存

  • 單一 char (2 bytes) 完整承載三個布林值 + 5 向方向。
  • 通關步驟檔 (*.bxs) 與設定檔 (PushBox.cfg) 直接存字串,無需序列化器,極適合行動裝置儲存空間有限的環境。
  • Pub.ToString(Step[]) 將陣列轉字串並 反轉(因堆疊彈出順序為 LIFO),回放時再 ToCharArray() 逐字還原 Step。

擴充建議

  1. 加入時間戳:若需精確重播速度,可擴充 struct StepEx { Step base; uint tick; }。
  2. 支援多箱同步推動:IsBox 改為 byte boxCount。
  3. 序列化為 Base64:跨平台傳輸時避免字元編碼問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved