How to add konami code in a website based on html?

前端 未结 10 1279
野性不改
野性不改 2020-12-13 01:21

I was asked to implement the Konami Code in a website I\'m currently working on. It should do the following:

  1. Change Background Image

  2. Play s

10条回答
  •  执念已碎
    2020-12-13 01:41

    as a typescript module

    const Konami = (() => {
        // up, up, down, down, left, right, left, right, b, a, enter
        const SEQUENCE: Array = [
            38,
            38,
            40,
            40,
            37,
            39,
            37,
            39,
            66,
            65,
            13,
        ];
    
        let head: number = 0;
        let isActive: boolean = false;
    
        let callback: Function | undefined;
    
        const start = (cb: Function): void => {
            if (isActive) {
                return;
            }
    
            window.addEventListener("keydown", onKeyDown);
    
            callback = cb;
            isActive = true;
        };
    
        const stop = (): void => {
            if (!isActive) {
                return;
            }
    
            isActive = false;
    
            window.removeEventListener("keydown", onKeyDown);
        };
    
        const onKeyDown = (event) => {
            if (event.keyCode === SEQUENCE[head]) {
                head++;
    
                if (head === SEQUENCE.length) {
                    if (callback instanceof Function) {
                        callback();
                    }
                    head = 0;
                }
            } else {
                head = 0;
            }
        };
    
        return {
            start,
            stop,
        };
    })();
    
    export default Konami;
    

    implementation:

    Konami.start(() => { alert("konami sequence entered!"); });

    notes: SEQUENCE is an array of the expected inputs. by using the head var, the order checking and number of correct inputs is maintained. it also provides a simple way to restart if input deviates from the sequence. it also eliminates the needs for a "count" var.

提交回复
热议问题