How to add a difficulty to a Javascript hangman game - javascript

I want to allow the user to select the difficulty of the game. Easy is words length 3-5, Medium is length 6-9, Hard is 10-15. The word is being pulled from an AJAX API. Also, I've consulted this example but am still struggling to apply it to my own. I included extra code because I'm not sure if I could add radio buttons that store the level and word.length that then updates the word retrieved from the api to be the correct length.
var api = 'https://hangman-api.lively.software';
//add alphabet to div
alphabet.forEach((i) => {
$('.hangman-letters').append(`<div id="letter-${i}">${i}</div>`);
});
//set up initial puzzle
newPuzzle();
//set up new puzzle when user clicks "start over"
$('#game-over-replay').click(function(){
newPuzzle();
});
//trigger game on clicking letter button
$('.hangman-letters div').click(function(){
submitLetter(this.innerHTML, this);
});
//trigger game on keypress
$(window).keypress(function(e){
var thisKey = String.fromCharCode(e.which);
if(alpha.indexOf(thisKey) > -1) {
submitLetter(thisKey, document.getElementById(`letter-${thisKey}`));
}
})
//functions
//handle clicked letter or keyboard input
function submitLetter(letter, thisLetterButton) {
var isCorrect = letterChosen(letter);
if(isCorrect) $(thisLetterButton).addClass('disabled correct');
else $(thisLetterButton).addClass('disabled');
if(remainingBlanks < 1) {
gameOver(true);
}
if(totalIncorrect >= hangmanParts.length + 1) {
gameOver(false);
}
}
//wipe variables and containers and set up new game
//now called after api call is complete
function setUp(){
$('.game-over').hide();
puzzleLetterContainers = [];
previouslyChosen = '';
totalIncorrect = 0;
remainingBlanks = puzzle.length;
$('.hangman-puzzle').html('');
$('#added-parts').html('');
$('.hangman-letters div').each(function(){
this.classList = '';
})
puzzle.split('').forEach((i) => {
var thisClass = "hangman-puzzle-letters",
placeholder = " ";
if(i == ' ' || i == '-') {
thisClass += ' space';
remainingBlanks--;
placeholder = i;
}
$('.hangman-puzzle').append(`<div class="${thisClass}">${placeholder}</div>`);
});
//var difficulty[] = new difficulty;
//var difficulty[1] = Easy;
//var difficulty[2] = Medium;
//var difficulty[3] = Hard;
puzzleLetterContainers = document.getElementsByClassName('hangman-puzzle-letters');
}

Related

Replace window when script ends JavaScript/HTML [duplicate]

This question already has answers here:
Window location replace - timeout help? Javascript question
(2 answers)
Closed 1 year ago.
Is there a way I can insert:
location.replace("https://www.google.com");
After all the functions in my javascript have run, aka when my script ends? I've tried putting it in different parts of my script but it just replaces it straight away.
This is my script currently (sorry it's so long its a text adventure game):
var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
var scenario = [
one: {
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
];
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo(scenario.one);
You can use ifelse statement as well as timeout for it
setTimeout ( "location()", 5000 );
function location( )
{
location.replace("https://www.google.com");
}
var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
buttons: [],
},
]
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
}
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
console.log("end of the game");
//location.replace("https://www.google.com"); // uncomment on your page
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo();
<div id="images"></div>
<div id="text"></div>
<div id="buttonBox"></div>
<input type="text" id="input"/>
Based on the code your posted you have 3 important parts:
the advanceTo function
the input.onkeypress event
the scenario list
for that I can suggest one of two changes:
change the scenario to an array (end and call the replace when there is no more elements)
add a end scenario (that calls the replace when it comes to it)
Array approach:
you can change the scenario to an array instead an object:
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
]
Also store the current frame in a variable (I suggest at the top of your code):
var currentFrame = 0;
So you can call advanceTo and starting the game (we are not passing the index anymore because is stored in the currentFrame variable:
advanceTo()
and change the logic of the advanced to a little bit:
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
At the end, you need to change your input.onkeypress event:
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};

How to make the click of 1 button change the .innerhtml of multiple things?

I'm new to javascript and programming and I'm attempting to make a program for my workouts. I want to be able to input the amount of sets, reps, and weight I lifted and then have the program output integers that are incrementally more challenging for my next workout. At the bottom I'm trying to get the enter button to change the .innerHTML of two different elements. Is this even possible?
`
var userMovement1 = document.getElementById("movement-1").value;
var userSet1 = document.getElementById("set-user-1").value;
var userReps1 = document.getElementById("reps-user-1").value;
var userWeight1 = document.getElementById("weight-user-1").value;
var enterButton = document.getElementById("enter-button");
//Function will calculate the reps for the next workout
function calculateFutureReps(performedReps) {
var futureReps = performedReps;
if (performedReps < 12) {
return futureReps += 2;
} else if (performedReps >= 12) {
return futureReps = 6;
}
}
//Function will calculate the weight for the next workout
function calculateFutureWeight(performedWeight) {
var futureWeight = performedWeight
if (performedWeight < 12) {
return futureWeight;
} else if (performedWeight >= 12) {
return futureWeight += 10;
}
}
//Getting the value of the functions and storing them in a variable
var newReps = calculateFutureReps(userReps1).value;
var newWeight = calculateFutureReps(userWeight1).value;
//Making that variable show up on the DOM
enterButton.onclick() = document.getElementById("reps-next-1").innerHTML = newReps;
enterButton.onclick() = document.getElementById("weight-next-1").innerHTML = newWeight;`
You can do something like this to handle the click and is a function to do whatever you want in there.
enterButton.addEventHandler('click', function() {
document.getElementById("reps-next-1").innerHTML = newReps;
document.getElementById("weight-next-1").innerHTML = newWeight;
});
`

JS : press enter and go to the next input

(Sorry if my english is bad)
I try to make a little game where you have to answer question in inputs. When you valid with the key "Enter", next input appear, and a new question in.
It is complicated to explain, so I leave you the test URL : nicolaslorand.com/bac.php
Here is my a part of my code :
var i = 1;
var j = 2;
$('#input'+i).keypress(function(event) {
console.log('input actuel :'+i);
console.log('input suivant :'+j);
if (event.which == 13) {
verification();
console.log("Touche entrée");
}
});
function verification(){
document.getElementById('input'+j).style.display = "block";
var index = $(".inputform").index(this) + 1;
$(".inputform").eq(index).focus();
var recup = document.getElementById('input'+i);
var verif = recup.value.toUpperCase();
var divLettre = document.getElementById('lettre');
var premiereLettre = divLettre.innerText || divLettre.textContent;
if ( verif.charAt( 0 ) === premiereLettre ) {
$("#input"+i).addClass('trueanswer');
i++; j++;
scoreTotal++;
console.log(i);console.log(j);
}
else{
$("#input"+i).addClass('falseanswer');
i++; j++;
console.log(i);console.log(j);
}
With this code, when I press enter, next input appear, but I have to write in the first input so that my answer is verified by the function.
You are using this inside function this refers to window object. i think you should use i instead of this
var index = $(".inputform").index(i) + 1;

My simple card game will not show the second card before it resets it's game board

My simple card game below will not show the picture of the second card before it goes on to display the alert message and then immediately reset its game board. Anyone able to help ?
Also, I'm kind of new to coding may anyone help to point out areas of code I could improve on?
var cards = ['queen', 'queen', 'king', 'king'];
var cardsInPlay = [];
var gb = document.getElementById('game-board');
//allows me to compare the pushed elements in the array cardsInPlay and erase all innerHTML when its done
var isMatch = function () {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert('You found a match!');
} else {
alert('Sorry, try again.')
};
document.getElementsByClassName('card')[0].innerHTML = "";
document.getElementsByClassName('card')[1].innerHTML = "";
document.getElementsByClassName('card')[2].innerHTML = "";
document.getElementsByClassName('card')[3].innerHTML = "";
};
//pushes the 'data-card-' of a card upon an eventlistener and "flip"/show the cards image based on its 'data-card' info. triggers function check if cards are a match.
var isTwoCards = function () {
cardsInPlay.push(this.getAttribute('data-card'));
if (this.getAttribute('data-card') === 'king') {
this.innerHTML = '<img src="kingcard.png" alt="King" />'
} else {
this.innerHTML = '<img src="queencard.png" alt="Queen" />'
};
if (cardsInPlay.length === 2) {
isMatch(cardsInPlay);
cardsInPlay = [];
};
};
//iterates and creates cards, while setting an attribute and eventListener
var createCards = function () {
for (var i = 0; i < cards.length; i++) {
var children = document.createElement('div');
children.className = 'card';
gb.appendChild(children);
document.getElementsByClassName('card')[i].setAttribute('data-card', cards[i]);
document.getElementsByClassName('card')[i].addEventListener('click', isTwoCards);
};
};
createCards();

How to Increase the numurical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row

How to increase the numerical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row? Data loads from firebase in tabular form.
Fiddle here, so you can understand it much better.
The script which loads (callback) data from firebase is given bellow
var LEADERBOARD_SIZE = 10;
var get_title = $('title').html();
var get_id = $('id').find('textarea').html();
// Create our Firebase reference
var scoreListRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
// Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
var htmlForPath = {};
// Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
function handleScoreAdded(scoreSnapshot, prevScoreName) {
var newScoreRow = $("");
newScoreRow.append($("").append($("").text(scoreSnapshot.val().name)));
newScoreRow.append($("").text(scoreSnapshot.val().url));
newScoreRow.append($("").text(scoreSnapshot.val().score));
// Store a reference to the table row so we can get it again later.
htmlForPath[scoreSnapshot.name()] = newScoreRow;
// Insert the new score in the appropriate place in the table.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
} else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}
// Helper function to handle a score object being removed; just removes the corresponding table row.
function handleScoreRemoved(scoreSnapshot) {
var removedScoreRow = htmlForPath[scoreSnapshot.name()];
removedScoreRow.remove();
delete htmlForPath[scoreSnapshot.name()];
}
// Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);
// Add a callback to handle when a new score is added.
scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
handleScoreAdded(newScoreSnapshot, prevScoreName);
});
// Add a callback to handle when a score is removed
scoreListView.on('child_removed', function (oldScoreSnapshot) {
handleScoreRemoved(oldScoreSnapshot);
});
// Add a callback to handle when a score changes or moves positions.
var changedCallback = function (scoreSnapshot, prevScoreName) {
handleScoreRemoved(scoreSnapshot);
handleScoreAdded(scoreSnapshot, prevScoreName);
};
scoreListView.on('child_moved', changedCallback);
scoreListView.on('child_changed', changedCallback);
// When the user presses enter on scoreInput, add the score, and update the highest score.
$("#scoreInput").keypress(function (e) {
if (e.keyCode == 13) {
var newScore = ($("#scoreInput").val());
var url1 = $("#urlInput").val();
var name = $("#nameInput").val();
$("#scoreInput").val("");
if (url1.length === 0)
if (name.length === 0) return;
var userScoreRef = scoreListRef.child(name);
// Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
userScoreRef.setWithPriority({
name: name,
url: url1,
score: newScore
}, newScore);
alert('Alternate Link for this App has been Succesfully submitted by you. By using this service you agree that you will Not Spam or Submit Links which refers to illegal or Copyrighted content.');
}
});
// delay function to make link clickable after 4 sec and also add onclick='HitCounter()' into links
var delay = 4000 //4 seconds
setTimeout(function () {
function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])/ig;
return text.replace(re, function (match, lParens, url) {
var rParens = '';
lParens = lParens || '';
var lParenCounter = /\(/g;
while (lParenCounter.exec(lParens)) {
var m;
if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
url = m[1];
rParens = m[2] + rParens;
}
}
return lParens + "" + url + "" + rParens;
});
}
var elm = document.getElementById('leaderboardTable');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
$(document).ready(function () {
$("a[href^='http://']").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
});
}, delay)
and the script which take care of URL Hit Counts is given bellow
function HitCounter() {
var get_id = $('id').find('textarea').html();
var HitCounterRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
var hits = $(tbody).find('tr').children('td').html();
if (hits == null) {
hits = 1;
} else {
hits++;
}
HitCounterRef.setWithPriority({
score: hits
}, hits);
};
I need some modification or improvement in this code so that when some one click on a link then correct corresponding 3rd column of same row should get a increment/increase in it's numerical value.
I also need something which could create connection b/w HitCounter and urls given in 2nd column of every row or initiate the HitCounter function when some one click on any of the link given in 2nd column of every row.

Categories

Resources