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

C# 開發智慧型手機軟體:推箱子遊戲(七)Common/Step.cs 步驟編碼與隱性轉換

     編輯:關於C語言

前言

本系列第七篇,介紹 Common/Step.cs,定義移動方向、設計模式列舉,以及核心結構 Step:以單一 char 高效編碼「方向、是否推箱、是否停留」三資訊,支援隱性雙向轉換。

完整原始碼


namespace Skyiv.Ben.PushBox.Common
{
    enum Direction { None, East, South, West, North }
    public enum Action { None, Create, Edit, Delete }

    public 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;
        }

        // 編碼對照表:
        // A B C D E  (方向 None~North, 無推箱、無停留)
        // F G H I J  (推箱)
        // K L M N O  (停留)
        // P Q R S T  (推箱+停留)

        public static implicit operator char(Step step)
        {
            char c = "ABCDE"[step.direct - Direction.None];
            if (step.isBox) c = (char)(c + 5);
            if (step.isStop) c = (char)(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)
            );
        }
    }
}

編碼設計解析

字元方向推箱停留索引 n
ANone否否0
BEast否否1
CSouth否否2
DWest否否3
ENorth否否4
F~J同上是否5~9
K~O同上否是10~14
P~T同上是是15~19

設計優勢

  1. 極致緊湊:單步驟僅 1 字元 (2 bytes UTF-16),20 種組合完整覆蓋。
  2. 隱性轉換:Step → char 序列化,char → Step 反序列化,程式碼簡潔:
    string s = string.Concat(steps.Select(st => (char)st));
  3. 無需額外庫:純 .NET 基礎類別,CF 完整支援。
  4. 人類可讀:字串 "BGKP..." 可直接觀察大致操作序列。

應用場景

  • 步驟記錄檔 (.bxs):每關通關步驟存為單行字串。
  • 撤銷/重做堆疊:Stack 直接 Push/Pop。
  • 回放引擎:讀取字串逐字轉 Step 執行動畫。
  • 網路傳輸:極小封包,適合低頻寬環境。

結語

Step 結構展示了「領域建模 + 位元級編碼 + 隱性轉換」的優雅結合。此模式廣泛適用於任何需高效序列化的離散狀態序列。

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