# The Konami Code Challenge

**URL:** <https://forum.kirupa.com/t/the-konami-code-challenge/641312>\
**Category:** programming\
**Created:** [December 11, 2019, 5:55pm UTC](https://forum.kirupa.com/t/the-konami-code-challenge/641312 "2019-12-11T17:55:35Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [December 13, 2019, 5:43pm UTC](https://forum.kirupa.com/t/the-konami-code-challenge/641312/2 "2019-12-13T17:43:54Z")

</div>

Below is my attempt at solving this, which I explain the _ins and outs_ of in the article:

```auto
let keys = {
  37: "left",
  38: "up",
  39: "right",
  40: "down",
  65: "a",
  66: "b"
};

let konamiCode = ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a"];
let keyCount = 0;

let timerID;

document.addEventListener("keydown", checkCode, false);

function checkCode(e) {
  let keyPressed = keys[e.keyCode];

  if (keyPressed === konamiCode[keyCount]) {
    keyCount++;

    // clear timer
    window.clearTimeout(timerID);

    // start timer with a 1 second delay before resetting state
    timerID = window.setTimeout(resetKeyState, 1000);

    // check if we are still on the right path
    if (keyCount === konamiCode.length) {
      cheatCodeActivated();
      resetKeyState();
    }
  } else {
    resetKeyState();
  }
}

function cheatCodeActivated() {
  alert("Cheat code activated!");
}

function resetKeyState() {
  console.log("Resetting state!");
  window.clearTimeout(timerID);
  keyCount = 0;
}

```

---

_[View the full topic](https://forum.kirupa.com/t/the-konami-code-challenge/641312)._
