C# 作的状态机

    技术2022-05-19  21

    看到别人用C写的状态机,网上关于状态机入门的知识基本上都以这个复制这个例子的.

     

    C#状态机代码:

    /******************************************************************************  * 状态机学习之一  * 输入2479后通过密码测试  * 源码(C语言):http://hi.baidu.com/juneshine/blog/item/6bff718bd5902f13c9fc7a14.html  * 只能使用主键盘上的数字键!  * tome 2011年4月19日  */  using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConTest1 {     public enum state     {         STATE1 = 1,         STATE2,         STATE3,         STATE4,         STATE5     };     public struct MYSTRUCT     {         public state cur_state;         public ConsoleKey input;         public state next_state;     };     class Program     {         static void Main(string[] args)         {             int i;             ConsoleKeyInfo key;             state machine;             MYSTRUCT[] st = new MYSTRUCT[5];             st[0].cur_state = state.STATE1;             st[0].input = ConsoleKey.D2;             st[0].next_state = state.STATE2;             st[1].cur_state = state.STATE2;             st[1].input = ConsoleKey.D4;             st[1].next_state = state.STATE3;             st[2].cur_state = state.STATE3;             st[2].input = ConsoleKey.D7;             st[2].next_state = state.STATE4;             st[3].cur_state = state.STATE4;             st[3].input = ConsoleKey.D9;             st[3].next_state = state.STATE5;             machine = state.STATE1;             do             {                 key = Console.ReadKey();                 if (key.Key == ConsoleKey.Escape)                 {                     break;                 }                 else                 {                     if ((key.Key >= ConsoleKey.D0) && (key.Key <= ConsoleKey.D9))                     {                         for (i = 0; i < 5; i++)                         {                             if ((key.Key == st[i].input) && (machine == st[i].cur_state))                             {                                 machine = st[i].next_state;                                 break;                             }                             else if (i == 4)                             {                                 machine = state.STATE1;                             }                         }                     }                     if (machine == state.STATE5)                     {                         Console.WriteLine("/nPassword correct, state transfer machine pass!");                         break;                                          }                 }             } while (true);             Console.Write("Press any key to exit...");             Console.ReadKey();         }     } }


    最新回复(0)