You are right; this is a more general thing: how to make common mathematical conceptions, structures/algorithms and design patterns in general programming and apply the same ideas to different projects; how to identify that the problem requires applications of some common patterns, structures, etc.
The bunch of problems you pose (quite reasonably, I think) is reduced to one such concept, well-known one:
finite-state machines (FSM). Please see:
http://en.wikipedia.org/wiki/Finite-state_machine[
^].
In one of my articles (recently updated), I pointed out that a FSM can be represented as the mathematical
relationship, which can be defined as any subset of a
Cartesian square based on a
finite set of elements considered as
states:
3.6 Cartesian Square[
^].
See also:
http://en.wikipedia.org/wiki/Cartesian_square[
^],
http://en.wikipedia.org/wiki/Finite_set[
^].
You can directly use it for implementation of your FSM, as this is the representation very convenient for implementation in code.
—SA