编辑: 请参阅我的其他帖子,了解始终有效的代码.下列不检测代码,如果它本身重叠(例如:"UP,UP,UP,DOWN,DOWN,左,右,左,右,B"将无法正常工作)
感谢Gevorg指出这一点.
如果它是如何识别你只关注的序列(我假设你知道如何从键盘输入),那么你可以得到如下的东西.
int[] sequence = {UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B};
int currentButton = 0;
boolean checkKonami(int keyPressed) {
//Key sequence pressed is correct thus far
if(keyPressed == sequence[currentButton]) {
currentButton++;
//return true when last button is pressed
if(currentButton == sequence.length) {
//Important! Next call to checkKonami()
//would result in ArrayIndexOutOfBoundsException otherwise
currentButton = 0;
return true;
}
}
else {
//Reset currentButton
currentButton = 0;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
无论何时注册按键,都会调用此功能,并传递已按下的键.当然,在适当的地方修改类型.
下面是一个检查Konami代码的类,包括" UP,UP,UP,DOWN等"的情况.
这适用于任何给定的序列.
import java.util.Map;
import java.util.TreeMap;
public class Konami {
static private int[] code =
{UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B};
static private Map<Integer, Integer>[] graph;
static private int currentNode = 0;
public static void main(String args[]) {
//Create graph
graph = generateSequenceMap(code);
//Call checkKonami(key) whenever a key is pressed
}
static public boolean checkKonami(int keyPressed) {
Integer nextNode = graph[currentNode].get(keyPressed);
//Set currentNode to nextNode or to 0 if no matching sub-sequence exists
currentNode = (nextNode==null ? 0 : nextNode);
return currentNode == code.length-1;
}
static private Map<Integer, Integer>[] generateSequenceMap(int[] sequence) {
//Create map
Map<Integer, Integer>[] graph = new Map[sequence.length];
for(int i=0 ; i<sequence.length ; i++) {
graph[i] = new TreeMap<Integer,Integer>();
}
//i is delta
for(int i=0 ; i<sequence.length ; i++) {
loop: for(int j=i ; j<sequence.length-1 ; j++) {
if(sequence[j-i] == sequence[j]) {
System.out.println("If at Node "+j+" you give me seq["+(j-i+1)
+ "] OR " + (sequence[j-i+1]) + " , goto Node " + (j-i+1));
//Ensure that the longest possible sub-sequence is recognized
Integer value = graph[j].get(sequence[j-i+1]);
if(value == null || value < j-i+1)
graph[j].put(sequence[j-i+1], j-i+1);
}
else
break loop;
}
}
return graph;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4178 次 |
| 最近记录: |