% square.pro - an example of asynchronous programing in Prolog using % a finite state machine % NOTE: you will need the quagent.pro library % This program is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by the % Free Software Foundation; either version 1, or (at your option) any % later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. % % In other words, you are welcome to use, share and improve this program. % You are forbidden to forbid anyone else to use, share and improve % what you give them. Help stamp out software-hoarding! :- consult('quagent.pro'). :- use_module(library(porter_stem)). %%% define our finite state machine - % it is a Moore machine, actions on the states % first and final state initial(start). final(stop). % define the actions at the states action(start,Q) :- writeln('start state'), q_walk(Q,100). action(one,Q) :- writeln('state one'), q_turn(Q,-90), q_walk(Q,100). action(two,Q) :- writeln('state two'), q_turn(Q,-90), q_walk(Q,100). action(three,Q) :- writeln('state three'), q_turn(Q,-90), q_walk(Q,100). action(stop,_) :- writeln('stop state: all done'). % define the edges edge(start,wait_stopped,one). edge(one,wait_stopped,two). edge(two,wait_stopped,three). edge(three,wait_stopped,stop). % define the condition for the transitions condition(wait_stopped,Q) :- wait_until_stopped(Q). %%% keep polling the events % base case wait_until_stopped(Q) :- % could be doing something smart here q_events(Q,E), parse_stopped_event(E). % recursive step wait_until_stopped(Q) :- % could be doing something smart here wait_until_stopped(Q). %%% parse event list for stopped event % base cases parse_stopped_event([]) :- fail. parse_stopped_event([H|_]) :- tokenize_atom(H,TokenList), member('STOPPED',TokenList). % recursive step parse_stopped_event([_|T]) :- parse_stopped_event(T). %%% main loop which uses the finite state machine state_machine(State,Q) :- final(State), action(State,Q). state_machine(State,Q) :- action(State,Q), edge(State,Label,NextState), condition(Label,Q), state_machine(NextState,Q). %%% run the program run :- q_connect(Q), state_machine(start,Q), q_close(Q).