progressive konami code - javascript

I am trying to create a .js file for a website that upon entering the konami code Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start(enter) it will embed a video.
However while entering the right keys the webpage should display something like "keep going", if a wrong key is entered it should display "wrong, try again", and allow them to start over.
I've manged to get the JavaScript working where upon entering the right code it displays an alert, and entering the wrong code displays a different code.
i've manged to get this much code using online resources but none of them explain how to get wrong, try again part
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
if (keys.toString().indexOf(konami) >= 0)
{
alert('Right');
keys = [];
};
if (keys.toString().indexOf(konami) < 0)
{
alert('Wrong');
keys = [];
}
}, true);
};
Any help would be greatly appreciated.

if (window.addEventListener) {
var index = 0;
var konami = [38,38,40,40,37,39,37,39,66,65,13];
window.addEventListener("keydown", function(e){
if (e.keyCode === konami[index])
{
index++; //valid key at the valid point
if (index == konami.length)
{
alert("Correct");
} else {
alert("Keep going");
}
} else {
// incorrect code restart
index = 0;
alert("Wrong");
}
});
}

You could do something like
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13".split(',');
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
console.log(e.keyCode);
var lengthOfKeys = keys.length -1;
if (konami[lengthOfKeys] == keys[lengthOfKeys])
{
alert('Right');
if(konami.length === keys.length){
alert('complete!');
}
}else{
alert('Wrong');
keys = [];
}
}, true);
};
fiddle here http://jsfiddle.net/b6kuZ/

This works for me:
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
konami_arr = konami.split(',');
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
var position = keys.length-1;
if(keys[position ] != konami_arr[position])
{
alert('Wrong');
keys = [];
}
else if (keys.join(',') == konami)
{
alert('Right');
keys = [];
};
}, true);
}
​jsFiddle exmaple

Having an alert come up every time a key is hit is very jarring. Instead, why mot have the validation of correct answers show up in a DIV, and only use an alert when the answer is incorrect.
function checker(){
if (kc==11){
kc=0; // This resets the sequence.
// The function for what you want to occur goes here.
}
}
function keyUp(e) {
var keynum;
if (window.event){keynum = event.keyCode;}
else if (e.which){keynum = e.which;}
for (i=0;i<222;i++){
// The 222 represents all the keys on the keyboard.
var kx=konamicode[kc]; // kx represents the current position in the code sequence.
var res=document.getElementById('response');
var dumb=wrong[kc];
if (keynum==i){
// Checks to see if key matches sequence, and resets sequence if it doesn't.
if (i!=kx){
res.innerHTML='';
alert(dumb); // Reprimands user, and resets the sequence.
kc=0;
}
else {
res.innerHTML=right[kc]; // Congratulates user, and advances the sequence.
kc++;
}
}
}
checker();
}
document.onkeyup = keyUp;
In the body of the page you will need to put a DIV to display that key strokes were validated as correct.
<div id="response"></div>

Related

Iterating through an array nested inside of an object

thank you for the help in advance! Please forgive me if this is a stupid question as I a JS noobie.
I am trying to cycle through an array of URL's that I have nested inside of an object. What I am expecting to happen is for the url's (which are google maps) to show up on my website and for the person using my website to be able to click back and forth between the different map URL's. Right now what's happening is the last item (a google maps url) of myCities.index is being properly displayed, but when I click my previous and next buttons it is going to a blank page. I have looked at my JS console and there are no visible errors there. Can anyone give me some advice as to how to fix this? My code is as follows.
const myCities = {
index:
[url1, url2, url3]
}
const prevButton = document.querySelector('.prevBtn');
const nextButton = document.querySelector('.nextBtn');
const map = document.getElementById("myCitiesss");
nextButton.addEventListener('click', nextCity);
prevButton.addEventListener('click', prevCity);
function prevCity() {
myCities.index--;
updateSrc();
checkButtons();
}
function nextCity() {
myCities.index++;
updateSrc();
checkButtons();
}
function updateSrc() {
map.src = myCities.index;
}
function checkButtons() {
prevButton.disabled = false;
nextButton.disabled = false;
if (myCities.index === 2) {
nextButton.disabled = true;
}if (myCities.index === 0) {
prevButton.disabled = true;
}
}
updateSrc();
checkButtons();
The problem is you're treating myCities.index as both the container of your data and as a counter (hence you're running incrementation/decrementation operations on it).
The counter should be a separate variable.
const myCities = [url1, url2, url3]; //<-- can now be a flat array
let index = 0; //<-- this is our counter, i.e. tracker
The relevant code changes are then: (I also took the opportunity to demonstrate some optimisations and efficiencies you can make)
nextButton.addEventListener('click', () => nextPrevCity('next'));
prevButton.addEventListener('click', () => nextPrevCity('prev'));
function nextPrevCity(which) { //<-- one function to handle both next and prev
which == 'next' ? index++ : index--;
map.src = myCities[index];
checkButtons();
}
function checkButtons() {
prevButton.disabled = false;
nextButton.disabled = false;
if (index === myCities.length - 1) //<-- check against array length, not fixed number 2
nextButton.disabled = true;
if (!index) //<-- because 0 is a falsy value, so same as "if (index === 0)"
prevButton.disabled = true;
}
[ -- EDIT -- ]
Forgot the following at the bottom of the code:
map.src = myCities[0];
checkButtons();

How do I make the multiple keydown event work without breaking?

$(document).on('keydown', function(event) {
const current = audios[Number(event.key) // audios is array of music files
current.currentTime = 0;
current.play();
});
I'm creating a drum application. If I press the number 2 with the keydown event, it will be activated. And while I hold down the number 2 and press 3, the number 2 will stop sounding. How can I make it happen? And Why do not this?
It looks like there's a syntax error in your code. const current = audios[Number(event.key) is missing a closing ].
Here is how I would approach it.
const pressedKeys = {};
$(document.body).keydown(function (evt) {
pressedKeys[Number(evt.key)] = true;
playSongs(pressedKeys);
});
$(document.body).keyup(function (evt) {
pressedKeys[Number(evt.key)] = false;
});
function playSongs(dict) {
for (let song in dict) {
if (dict[song] === true) {
audios[song].currentTime = 0;
audios[song].play();
}
}
}
This code keeps track of keys in a dictionary. Whenever a keydown is registered it adds it to the dictionary. Right afterwards, playSongs finds all keys that are true and plays that song.

Limit consecutive characters on keypress with javascript

i wrote this code for an information booth at a park, it works on html5 and javascript
function myFunction() {
var name = document.getElementById('name').value;
var nameFilter = /^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$/g;
if(nameFilter.test(name)) {
$('#name').keydown(function (e) {
if (e.keyCode == 8 || e.keyCode == 46) {
$(this).unbind(e).keypress();
}
else {
e.preventDefault();
//return false;
}
});
}
};
it is supposed to prevent more than one consecutive characters (the booth keyboard is kinda broken and on key press it puts like 3 to 5 times the pressed key)
so far i've accomplished to limit it to two characters, but then thanks to preventDefault() it does nothing, i used an unbind to restore it but still i've accomplished nothing and i need help with this, whether it be by this mean of any other
This version accounts for capitalizing letters with the shift key
var nameElement = $('#name');
var wasShiftKeyPressed;
var nameAfterFirstKeyDown;
nameElement.keydown(function(e) {
wasShiftKeyPressed = e.shiftKey;
setTimeout(function() {
nameAfterFirstKeyDown = nameAfterFirstKeyDown ? nameAfterFirstKeyDown : nameElement.val();
});
})
nameElement.keyup(function() {
if (wasShiftKeyPressed) {
wasShiftKeyPressed = false;
nameAfterFirstKeyDown = nameElement.val(); //Otherwise capitalization only works for first letter
}
else {
nameElement.val(nameAfterFirstKeyDown);
nameAfterFirstKeyDown = "";
}
});

There must be a better way - change search as user input changes

I have a search filter that hides s as the user enters text into a form input. I need it to be dynamic, so that as the user changes their input, the filter refreshes. I accomplished this by having the filter clear on every keyup, but that causes the filter to be delayed and to flash when a word is typed quickly into the filter. You can see what I mean here:
http://cambridgefellows.com/directory-of-fellows/
Here is my jquery:
$(document).ready(function() {
$('input[name=searchFilterInput]').val('');
$('input[name=searchFilterInput]').keyup(function() {
var searchFilterVal = $('input[name=searchFilterInput]').val();
searchFilterVal = searchFilterVal.replace(/ /g, '-');
searchFilterVal = searchFilterVal.toLowerCase();
$('tr.hide').fadeIn('slow').removeClass('hide');
if(searchFilterVal == '') {
$('tr.hide').fadeIn('slow').removeClass('hide');
} else {
$('tr.fellows').each(function() {
var pattern = $(this).attr('class'); // the pattern to be matched
var match = pattern.match(searchFilterVal);//If pattern matches it returns the match
if(!match) {
$(this).fadeOut('normal').addClass('hide');
} else {
}
});
}
});
$('#searchForm').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
});
I think there must be an easier way to handle this so that the filter dynamically updates as the user enter or alters their search text. Can someone more experienced than me look at this an enlighten me to the obvious thing that I'm overlooking? Thank you so much for your help.
Looks like you need a setTimeout and clearTimeout.
var timer;
$('input[name=searchFilterInput]').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var searchFilterVal = $('input[name=searchFilterInput]').val();
searchFilterVal = searchFilterVal.replace(/ /g, '-');
searchFilterVal = searchFilterVal.toLowerCase();
$('tr.hide').fadeIn('slow').removeClass('hide');
if(searchFilterVal == '') {
$('tr.hide').fadeIn('slow').removeClass('hide');
} else {
$('tr.fellows').each(function() {
var pattern = $(this).attr('class'); // the pattern to be matched
var match = pattern.match(searchFilterVal);//If pattern matches it returns the match
if(!match) {
$(this).fadeOut('normal').addClass('hide');
} else {
}
});
}
}, 300);
});
That way whenever a user hits the next key, the timeout will be cleared from the previous keypress and the code will only execute for the current keypress.
Reduce the milliseconds if you feel it's not updating fast enough.

How to get my loop to start from the beginning after error detected

I am trying to get my loop to restart when it comes across an user input error. I need it to restart at the very beginning and not just the last question.
So below when it says validImput = false this is where I am trying to get it to restart.
{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {
// ask first question
var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
if (isNaN(orderProductCodeArr)) {
alert("input is not a valid number");
validImput = false
} else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
alert("code does not match any item");
validInput = false;
}
// ask second question
else if(validInput == true) {
var item = PRODUCT_LIST[orderProductCodeArr];
alert("item is: " + item);
}
// get quantity input
var quanityArr = parseInt (prompt('Enter quality amount'),10);
if (isNaN(quanityArr)) {
alert("input is not a valid number");
validInput = false;
}
} else {
document.writeln('still to come')
}
}
The usual method of starting something over is some sort of loop construct, often using while like this:
while (true) {
// your loop code here
// you can use break; to break out of the while loop
// anywhere to stop repeating
// you can use continue; to jump to the next iteration immediately
}
Or, sometimes you use a loop condition like this:
var doAgain = true;
while (doAgain) {
// within the loop, you set doAgain to false when you are done
// and don't want to repeat the loop again
}
try
function test()
{
for(var s=0;s<5;s++)
{
try
{
//body of the for loop
}catch(e){s=0;}
}
}

Categories

Resources