简体   繁体   中英

Keep history/order of keys pressed

I have an array with keyboard combinations and this should validate to press keys exactly in the order of the array example

var listkeys = ['left', 'right', 'bottom', 'top'];

if(validate key){
    continue
}

the order of the array is important if they are wrong by pressing in the order of the arrows then as I continued not more and sends you an error

I am a newbie in javascript I hope I can help enormously grateful

Typically, I don't respond to posts that ask for Do-It-All solutions, but I wrote it out and didn't want it to go to waste. Here is a little something to get you started.

// Valid combination of keys
var valid_combo = ['left', 'right', 'bottom', 'top']; 

// Stack that stores the last 4 key inputs, including non-arrow keys
var history = [];  

// Maps arrow key direction strings to char code
var keys = []; 

keys[37] = 'left';
keys[38] = 'top';
keys[39] = 'right';
keys[40] = 'bottom';

$(window).keyup(function(e) {

    var key = e.which;

    if (key >= 37 && key <= 40) 
    {
        history.push(keys[key]);
    }
    else
    {
        history.push("derp");
    }

    if (history.length > 4) history.shift();

    // Array equality using Option 1 - http://stackoverflow.com/a/10316616/773702
    if (JSON.stringify(valid_combo) == JSON.stringify(history)) 
    {
        console.log("Valid key combination");
    }
});

See it in action on jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM