Interview Q: Detecting a fighting game moveset - algorithm

I got this as an interview question and I'm wondering what the optimal way of designing this system would be. The problem:
Say you have a fighting game where certain button combinations represent a special move. Implement 2 functions register_move([button combo],movename) which takes in a list of button inputs and a movename string and on_keypress(button) which registers the current keypress and prints a movename if a button combo has been activated. The buttons are represented as characters: 'U','D','L','R','A','B'
Example:
register_move(['A','B','U'],"Uppercut")
on_keypress('A')
on_keypress('B')
on_keypress('U') -> print "Uppercut"
you can assume moves are registered before on_keypress so you don't have to retroactively look back at the previous keypresses. You can use any language you like

Build a Deterministic Finite State Automaton. The initial state is "no keys recognised". On each keypress, transition into a new state; if it is a final state you have a move. All undefined transitions transition into the starting state. For your example,
S --(a)--> A
A --(b)--> AB
AB --(u) --> ABU: process "Uppercut", move to S
X --(x)--> S
where X is any state, x is any input not otherwise covered by the rules.
More practically and less theoretically, you will end up with a trie, so using a trie library should be sufficient. Root is "no input", walk it until a leaf, or restart on a mispress.

Considering the limited number of moves, you don't need a super efficient finite state machine to handle this.
You could simply store the strings in register_move, and have on_keypress memorize the last potentially valid sequence.
If the current key sequence is the prefix of at least one move (for instance "AB" being a prefix of "ABU"), you're done (just wait for the next keypress to see if a combo is reached).
If the sequence is no prefix, reset the sequence to the last keypress (for instance "ABD" -> "D"). This clears previous keypresses that correspond to no moves.
If the sequence corresponds to a move, perform the move (well, print it at least) and reset the sequence.
This would require to do a prefix search on every possible move combo, which is very quick if you have only a dozen or so. If for some reason you want to be quicker, you can indeed turn your list of combos into a prefix tree, but it would require a lot more code for little gain.

Related

Mutli-track Turing Machines

I'm doing my homework, and i have a problem with multi-tape (multi-track) Turing Machine:
We have multi-tape Turing Machine, which always before moving a head left, writes a blank symbol.
Does this machine recognise the same class of languages as standard Turing machines?
Do you have any idea how to prove it? Certainly standard Turing Machine recognise a recursively enumerable language (Typa-0 in Chomsky hierarchy).
Without loss of generality we can supopose that TMs do not go further to the left than the first input symbol.
Consider the following PDA P:
P simulates the TM until the first step to the left and puts the output on the stack.
The TM moves to the left are done via pops from the stack.
When moving to the right again, the TM reads only blanks until it reaches the first untouched input symbol. P can do this in one single step.
For steps 2 and 3 we need the following: the state and direction in which the TM exits the block of blanks (between the last non-erased input symbol on the left and the first untouched one on the right) depends on the number of blanks in this block. There are infinitely many possibilities. However, there can only be a finite class of combinations of entrance/exit states and directions. Probably this can be coded into the PDA's finite control and updated every time another blank is written.
If this is correct, these TMs only accept the class of context-free languages. But these details would have to be worked out to really prove this.

Finite state machines how to implement minimum and maximum hits

I'm trying to implement a fsm and it's going fine. I can enter strings and see if they are valid and all that kind of stuff.
However regular expressions (which are fsms) have this feature where you can specify how many times a certain character may occur for example a{2,4} would accept "aa" and "aaa" but not "aaaaa" and "a"
I can imagine having a counter on edges that count how many times they have been hit and use this to deny any characters after the counter has hit a certain number but you can't implement minimum this way because it would always block the first character (unless minimum is 0).
Does anyone know a way to implement this feature?
it also has to work for really big numbers like a{1,99999999999}
To my understanding, this kind of constraint cannot be implemented dynamically in a finite state machine; parts of the FSM would have to be statically expanded. In your example, for a{2,3} three different separate FSMs would have to be built, one accepting aa, the second one accepting aaa and the third one accepting aaaa; these would then have to be made alternatives in the final FSM via some empty transitions. The reason for this is the fact that the FSM itself does not store the path by which its current state was reached, which means that a paremeterized form of the pattern a{i,j} cannot be checked.

Viterbi algorithm for real-time applications

I know that given an HMM and an observation, Viterbi algorithm can guess the hidden states sequence that produce this observation. But what about the case you want to use it real-time? I mean finding the hidden states step by step. Every time an observation symbol is on the input, a hidden state is guessed, without knowing the whole observation sequence that's coming next.
I want to use that for an audio application that is running in real time so the observation will be a sequence of values of an audio feature at each time frame.
If you are interested in predicting what the hidden state is at time T, when you see the observation O_T, then you have data O_1, ..., O_{T-1}, O_T. Now the most likely state is found with forward backwards, where the backward variable is simply 1, because we can't see into the future. In summary, we have P(We are in hidden state i at time T) = \alpha_T(i) / P(O_1, ..., O_T | \lambda), where P(O_1, ..., O_T| \lambda) = \sum_{i=1}^n \alpha_T(i). Then the max index over all i's of P(We are in hidden state i at time T) will be your hidden state.
Please refer to http://courses.media.mit.edu/2010fall/mas622j/ProblemSets/ps4/tutorial.pdf for the formal notation.
Please let me know if this is what you were after, or if you had something else in mind. If you just wanted to find the best sequence of states in realtime, just compute the alpha variables, no need to look into the future for that.

Cycling LED Modes using ControllerMate

I'm using ControllerMate with a Nostromo (Belkin) n52 (NOT the te version) Speedpad on an iMac running Snow Leopard.
The official SpeedPad configuration software doesn't run beyond Tiger, or at least, it doesn't run on Snow Leopard due to the kext failing to load properly, hence the attempt at using ControllerMate.
The official SpeedPad configuration software has the capability to load 1 unique set of keys per "page", where there are 4 pages. This ultimately led me to be able to do things like basic key mapping on the first page, key combinations on the second, macro'ing on the third, and I set up some global shortcuts for my music player, and bound those same shortcuts on the last page of the Speedpad.
Pages were represented by the currently lit LED on the unit;
No LEDs On / Red LED On / Green LED On / Blue LED On
I'm attempting to use the Logic functions of ControllerMate in order to recreate this same behavior. Clicking a button bound to this routine will cause the LEDs to start cycling in the order listed above, ultimately circling around and restarting at no LEDs on.
I'm going to explain this as best I can so that the basic principles of programming/logic here could feasibly be answered by any individual here, but I might fail, and you might need to familiarize yourself with ControllerMate first :P.
ControllerMate presents you with a grid, where you simply drag objects in. It's a visual programming canvas. For example, my Canvas has 4 blocks on it currently;
Nostromo SpeedPad 2
Keypad LeftAlt
This is the key that corresponds to the large Orange button above the DPad. It's on the Canvas so I can dump other elements into it, and get elements out of it.
It's a basic Input/Output system with snapping elements.
Num Lock
Caps Lock
Scroll Lock
These represent the LEDs. When these blocks turn "on", the related LED on the SpeedPad lights up.
For example, if I connect one Lock block, or all of them, directly to the LeftAlt block, pressing the "LeftAlt" button on the SpeedPad turns on one/all of the LED light(s) for the duration that it's held.
ControllerMate actually has a wonderful guide of explaining the "Blocks" and showing what they look like at http://www.orderedbytes.com/controllermate/help/?show=blocks
The Logic blocks I have to work with are as follows:
AND
NOT
OR
XOR
ON/OFF Gate
ON/OFF Latch
1:2 Selector
Toggle
Most of these are self explanatory already, but just in case they aren't, please consult the above link to get the specific Block Reference (My Rep. currently prevents me from linking each of the above elements).
I'm thinking that I'm going to have success with using a series of Toggles and Gates, but I haven't quite been able to interconnect them properly to consistently behave in a perfect loop of invocation.
Bonus Points if you're really feeling up to it (you'll get an accepted answer for satisfying only the primary question, promise!):
Not only a linear On/Off per LED, but a complete permutation of all On/Off combinations;
All Off
Red On Blue Off Green Off
Red On Blue On Green Off
Red On Blue Off Green On
Red On Blue On Green On
Red Off Blue On Green Off
etc.
[edit]
If anyone with suitable rep could create/add the "ControllerMate" tag to this question I'd sure appreciate it.
I figured it all out, it was quite a long time coming. Let's break it into a few different topics;
(1) Keybinding / Key Representation
(2) Blocks Used
(3) Logic
First, I set up a simple key remap, but that example failed because pressing the Speedpad 02 key, would input it's original mapping (q) and the re-map I defined (w). I started crawling over the ControllerMate Forums, and I stumbled on a
great couple of posts, which would make better starting points than the .cmate definition files that are easy to find, but I digress…
After ripping my hair out looking for a setting I had missed, program preferences, or what have you, I looked on the forums and came across a great thread. After reading it, I took the 30 second and disabled all the buttons for the "keyboard" palette portion and the "mouse" palette portion that didn't actually exist.
This means disabling all but the 15 numbered keys, plus the orange key, plus the dpad for the keyboard portion, and disabling all the mouse keys for the mouse portion. I'm going to send this new map file to Ken (the ControllerMate developer).
After doing this, and naming the keys something sane so they're properly represented as the key they're labeled, the remaps work as expected. Speedpad 02 only enter my remaped key of w, and nothing else!
This first step finally was finished.
Second and third, I sat down and figured out a creative solution to the LED task;
I'm using exactly zero of the logic blocks above. I use meta blocks (Key blocks, group blocks) and math.
When pressing the Orange thumb button, a "accumulator" block runs, from 0 to 3, stepping by 1 each push.
That accumulator has 3 outlets, each going to a subtraction block. The first subtraction block subtracts 1, the second subtracts 2, the third subtracts 3.
All of those subtractor blocks connect directly to a "Value Selector". If the value is zero, that particular selector turns on.
Thus, when I've pushed the orange button once, the accumulator provides a value of 1, which goes to all of the subtractors, but more specifically the one controlling the Red LED subtracts 1, and totals 0, so it's Value Selector enables, which enables the "Num Lock" (Red
LED) light.
The LED Outlets connect to a constant number value block (again, the -1 subtraction stack connection ultimately provides a constant value of 1, the -2 subtraction stack ends up at a constant value of 2, -3 goes to 3.
All three of these constant value blocks goes to a series of 4 Addition blocks, Red LED/Constant 1 has four outputs, to all four Addition blocks. Blue LED/Constant 2 has four outputs that go to all four Addition blocks, and Green LED/Constant 3 [...].
Then, a configuration page can be placed on the canvas, in which case I moved the "remap" page onto the canvas, and attached it to an addition->expect 0 value selector block, meaning that if the addition equals zero, that particular value selector is on. When all LEDs are
off, the top half constant value blocks are disabled, and don't provide their particular value.
Now, I just need to figure out what to bind to the other three modes I was so desperately working on.
Picture of the ControllerMate Canvas;
http://vxjasonxv.com/images/ControllerMateSC2.png

Tree Algorithm

I was thinking earlier today about an idea for a small game and stumbled upon how to implement it. The idea is that the player can make a series of moves that cause a little effect, but if done in a specific sequence would cause a greater effect. So far so good, this I know how to do. Obviously, I had to make it be more complicated (because we love to make it more complicated), so I thought that there could be more than one possible path for the sequence that would both cause greater effects, albeit different ones. Also, part of some sequences could be the beggining of other sequences, or even whole sequences could be contained by other bigger sequences. Now I don't know for sure the best way to implement this. I had some ideas, though.
1) I could implement a circular n-linked list. But since the list of moves never end, I fear it might cause a stack overflow ™. The idea is that every node would have n children and upon receiving a command, it might lead you to one of his children or, if no children was available to such command, lead you back to the beggining. Upon arrival on any children, a couple of functions would be executed causing the small and big effect. This might, though, lead to a lot of duplicated nodes on the tree to cope up with all the possible sequences ending on that specific move with different effects, which might be a pain to maintain but I am not sure. I never tried something this complex on code, only theoretically. Does this algorithm exist and have a name? Is it a good idea?
2) I could implement a state machine. Then instead of wandering around a linked list, I'd have some giant nested switch that would call functions and update the machine state accordingly. Seems simpler to implement, but... well... doesn't seem fun... nor ellegant. Giant switchs always seem ugly to me, but would this work better?
3) Suggestions? I am good, but I am far inexperienced. The good thing of the coding field is that no matter how weird your problem is, someone solved it in the past, but you must know where to look. Someone might have a better idea than those I had, and I really wanted to hear suggestions.
I'm not absolutely completely sure that I understand exactly what you're saying, but as an analagous situation, say someone's inputting an endless stream of numbers on the keyboard. '117' is a magic sequence, '468' is another one, '411799' is another (which contains the first one).
So if the user enters:
55468411799
you want to fire 'magic events' at the *s:
55468*4117*99*
or something like that, right? If that's analagous to the problem you're talking about, then what about something like (Java-like pseudocode):
MagicSequence fireworks = new MagicSequence(new FireworksAction(), 1, 1, 7);
MagicSequence playMusic = new MagicSequence(new MusicAction(), 4, 6, 8);
MagicSequence fixUserADrink = new MagicSequence(new ManhattanAction(), 4, 1, 1, 7, 9, 9);
Collection<MagicSequence> sequences = ... all of the above ...;
while (true) {
int num = readNumberFromUser();
for (MagicSequence seq : sequences) {
seq.handleNumber(num);
}
}
while MagicSequence has something like:
Action action = ... populated from constructor ...;
int[] sequence = ... populated from constructor ...;
int position = 0;
public void handleNumber(int num) {
if (num == sequence[position]) {
// They've entered the next number in the sequence
position++;
if (position == sequence.length) {
// They've got it all!
action.fire();
position = 0; // Or disable this Sequence from accepting more numbers if it's a once-off
}
} else {
position = 0; // missed a number, start again!
}
}
You might want to implement a state machine anyway, but you don't have to hardcode state transitions.
Try to make a graph of states, where link between state A to state B will mean A can lead to B.
Then you can traverse graph at runtime to find where player goes.
Edit: You can define graph node as:
-state-id
-list of links to other states,
where every link defines:
-state-id
-precondition, a list of states what must be visited before going to this state
What you're describing sounds very similar to the technology tree in a game live Civilization.
I don't know how the Civ authors built theirs, but I'd be inclined to use a multigraph to represent possible 'moves' - there will be some you can start at with no 'experience', and once you're in them, there will be multiple paths through to the end.
Draw-out what potential options you can have at each stage of the game, and then draw lines going from some options to others.
That should give you a start on implementation, as graphs are [relatively] easy concepts to implement and utilize.
Sounds like a neural network. You could create one and train it to recognize the patterns that cause the various effects you are looking for.
What you're describing sounds somewhat similar to a dependency graph or a word graph. You might look into those.
#Cowan, #Javier: Nice idea, mind if I add to it?
Let the MagicSequence objects listen to the incoming stream of user input, that is notify them of the input (broadcast) and let each of them add the input to there internal input stream. This stream is cleared when the input is not the expected next input in the pattern that would have the MagicSequence fire its action. As soon as the pattern is completed, fire the action and clear the internal input stream.
Optimize this by only feeding input to the MagicSequences that are waiting for it. This could be done two ways:
You have an object that lets all MagicSequences connect with events that correspond with numbers in their patterns. MagicSequence(1,1,7) would add itself to got1 and got7, for example:
UserInput.got1 += MagicSequnece[i].SendMeInput;
You could optimize this such that after each input MagicSequences deregister from invalid events and register with valid ones.
create a small state machine for each effect that you'd want. at each user action, 'broadcast' it to all state machines. most of then won't care, but some will advance, or maybe go backwards. when one of them reaches it's goal, produce the desired effect.
to keep the code neat, don't hardcode the state machines, instead build a simple data structure that encodes the state graph: each state is a node with a list of interesting events, each one points to the next state's node. Each machine's state is simply a reference to the appropriate state node.
edit: It seems Cowan's advice is equivalent to this, but he optimises his state machines to express only simple sequences. seems enough for your specific problem, but more complex conditions could need a more general solution.

Resources