FRI
08:35 13
2017
08-18

JavaScript Konami Code

The Konami Code is a sequence of button presses that triggered a cheat of some description in many Konami games. On the title screen you'd press Up, Up, Down, Down, Left, Right, Left, Right, B and A on your controller and the cheat would be activated/revealed/whatever.

Many web folks like to include a hidden response to the Konami Code and it's not a terribly difficult thing to do, so here's how we go about it:

This simple piece of JavaScript calls a function called konamiGo(); whenever the correct sequence of keys is pressed. Here's what happens line by line:

  1. Define a function called konamiCheck() which takes note of an event.
  2. Get the value of the keypress that spawned the function.
  3. Add a string version of this value to a variable called konami.
  4. Compare the last 10 keys (2 bytes each) to our desired sequence, '38384040373937396665';
  5. If they match, spawn konamiGo();

The two lines after the function set the konami variable as a global and attach the konamiCheck() function to the onkeydown event so that it is called every time the user presses a key.

Why are we comparing against 38384040373937396665? Well that's the ascii codes for all of the keypresses in the Konami Code sequence - Up is 38, Down is 40 and so on. Assuming the user enters the code correctly they will match this value and spawn your surprise.

All that's left for you to do is write your own konamiGo(); function to do something interesting.

Bonus: Tweetable Version

For the minimalists amongst you, here's the Konami Code in 119 characters (once you remove the CrLf):

Leave a comment if you use this to add a surprise to your site.

 

bl0ke

boing

Tested on desktop versions of Chrome, IE11, Edge, Safari, Opera and Firefox. Any problems are entirely your own.

Buying from Amazon? Enter the product code into the box below to earn me a few pence and support this site!
https://www.amazon.co.uk/exec/obidos/ASIN//bl0g-21