I'm making a game and want to implement cheat codes like the Konami code.
But how do I check for that sequence of keystrokes?
I want it to work so that if a player just types the code it will trigger.
Thanks in advance!
EDIT: See my other post for code that always works. The following doesn't detect the code if it overlaps with itself (for instance: "UP, UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B" wouldn't work)
Thanks to Gevorg for pointing this out.
If it's how to identify the sequence that you are concerned with only (I'll assume you know how to get input from the keyboard) then you can have something as follows.
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;
}
Call this function whenever a key press is registered, passing the key that has been pressed. Of course modify the types where appropriate.
I'm sure you're past this project now, but I just implemented this into one of my assignments and wanted to leave it for others to find. This solution logs the last n keystrokes (defined here as 10) into a circular array and returns true when they match our code. You could just as easily pass in different lengths and codes as part of the method (but this implementation didn't require it). I used ^ ^ v v < > < > b a.
public class Code {
private static int[] history = new int[10];
private static int front = 0;
private static int size = 0;
// Here is the Code they must enter (ascii vals for konami).
private static int[] code = {38, 38, 40, 40, 37, 39, 37, 39, 66, 65};
// Static class. No constructor.
private Code(){}
// Adds key-press into history buffer. If code is matched, return true.
public static boolean add(int e){
// Write the value into our key history.
history[(front + size) % 10] = e;
// Stop growing at length 10 and overwrite the oldest value instead.
if (size < 10){
size++;
} else {
front = front + 1 % 10;
}
// Compare our history (from the current front) to the code (from 0)
for(int i = front; i < front + size; i++){
if (history[i % 10] != code[i-front]){
// Any 1 mismatch will abort
return false;
}
}
// Make sure we've logged enough keystrokes so it doesn't fire off
// if your first key press matches the code.
if (size < 10){
return false;
}
return true;
}
Enjoy! :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With