如何检查一系列击键

Nol*_*oxs 9 java keyboard io

我正在制作一款游戏,并希望实现像Konami代码这样的作弊码.

但是如何检查按键序列?

我希望它能够工作,这样如果玩家只是键入代码就会触发它.

提前致谢!

Wae*_*elJ 5

编辑: 请参阅我的其他帖子,了解始终有效的代码.下列不检测代码,如果它本身重叠(例如:"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)

无论何时注册按键,都会调用此功能,并传递已按下的键.当然,在适当的地方修改类型.

  • UP,UP,UP,DOWN,DOWN,LEFT,RIGHT,LEFT,RIGHT,B打破你的算法,不是吗?第三个U将currentButton带回0并且无法识别模式.请注意,如果您丢弃第一个UP,则序列有效! (2认同)

Wae*_*elJ 5

下面是一个检查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)