Rubik's cube 5x5x5 edgeswap added.
[zzandy.git] / fsm.html
blobfc2e839d678bfd945cdb24e927c266b84dcf51a0
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
4 <head>
5 <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
6 <link rel="stylesheet" href="style/pixelless.css" type="text/css"/>
7 <script type="text/javascript" src="script/util.js"></script>
8 <title>Finite State Automata</title>
9 </head>
10 <body>
11 <div id="container">
12 <div class="content header">
13 <h1>Finite State Automata</h1>
14 </div>
16 <div class="content">
18 </div>
19 </div>
20 <div id="footer">
21 <div class="content">
22 &copy; Copyright
23 </div>
24 </div>
25 <script type="text/javascript" language="JavaScript">
26 function Fsm( state )
28 this.transitions = {};
29 this.handlers = {};
31 this.current = state;
32 this.previous = null;
34 this.state = {};
37 Fsm.prototype.addTransition = function( from, to, event )
39 if( !(from in this.transitions) )
40 this.transitions[from] = {};
42 if( event in this.transitions[from] && this.transitions[from][event] != to )
43 throw new Error('Cannot add conflicting transition.');
45 this.transitions[from][event] = to;
50 Fsm.prototype.turnFrom = function( state )
52 return new TransitionHint(this, state);
55 Fsm.prototype.on = function( state, handler )
57 this.handlers[state] = handler;
60 Fsm.prototype.handle = function( event )
62 if( event in this.transitions[this.current] )
65 this.previous = this.current;
66 this.current = this.transitions[this.current][event];
68 if( this.current in this.handlers )
70 try {
71 this.handlers[this.current].call(this.state, this.state);
73 catch( ex )
75 if( console !== null )console.log(ex);
81 function TransitionHint( fsm, state )
83 this.fsm = fsm;
84 this.startState = state;
87 TransitionHint.prototype.to = function( state )
89 return new Transition(this.fsm, this.startState, state);
92 function Transition( fsm, startState, endState )
94 this.fsm = fsm;
95 this.startState = startState;
96 this.endState = endState;
99 Transition.prototype.on = function( event )
101 this.fsm.addTransition(this.startState, this.endState, event);
102 return new TransitionHint(this.fsm, this.endState);
105 var bot = new Fsm('seeking');
107 bot.turnFrom('seeking')
108 .to('attacking').on('target_encountered')
109 .to('fleing').on('health_low');
111 bot.on('attacking', function( state ) {
112 if( this != state )
113 console.log('noooooo');
114 else
115 console.log('yes.');
118 bot.handle('target_encountered');
120 </script>
121 </body>
122 </html>