Rock Paper Scissors game loop - javascript

I'm working on a task to build a Stone,Paper,Scissors Game.
The game is supposed to run in 3 possible modes. best of 3 / best of 5 and endless games.
My code works fine until the point where I reset the game to begin a new game.
For a reason which I can not figure out, it plays multiple instances of my game, each time I call the game() function.
(after the game is over - a reset game button appears and the game mode needs to be reseleted)
I've added the entire project to this https://jsfiddle.net/vydkg3bz/, since I don't manage to pinpoint where the issue is.
I believe, due to all the extra logging I added, that the problem is somewhere in the game() function, as I tried to replace most of the code around it, with the same result.
Maybe someone has a moment to review my code and give me a hint where I should look?
// global variables
var choicesObj = {
Rock: "url('./img/stone.png')",
Paper: "url('./img/paper.png')",
Scissors: "url('./img/scissors.png')",
}
var choices = Object.keys(choicesObj);
var moveAI;
var movePlayer;
var winnerRound;
var winnerGame;
var roundCount = 0;
// actual game
function game(requiredWins) {
console.log("game");
enabler()
var inputs = document.querySelectorAll(".inputButton");
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function() {
movePlayer = this.id
handleClick(movePlayer)
});
}
// checking choice, display choice IMG, call compareChoices function
function handleClick(buttonID) {
console.log("handleClick");
moveAIfunc()
movePlayer = buttonID;
console.log('movePlayer: ' + movePlayer);
console.log('moveAI: ' + moveAI);
document.getElementById("mainImgPlayer").style.backgroundImage = choicesObj[movePlayer];
document.getElementById("mainImgAI").style.backgroundImage = choicesObj[moveAI];
compareChoices(moveAI,movePlayer);
console.log("requiredWins", requiredWins);
gameEnd();
displays();
}
// AI control
function moveAIfunc() {
moveAI = choices[Math.floor(Math.random() * choices.length)]
}
// compare choices
function compareChoices(a, b) {
console.log("compareChoices");
a = choices.indexOf(a);
b = choices.indexOf(b);
console.log("requiredWins", requiredWins);
roundCount++;
if (a == b) {
winnerNone()
return;
}
if (a == choices.length - 1 && b == 0) {
winnerPlayer()
return;
}
if (b == choices.length - 1 && a == 0) {
winnerAI()
return;
}
if (a > b) {
winnerAI()
return;
}
else {
winnerPlayer()
return;
}
}
// game end
function gameEnd() {
console.log("gameEnd");
console.log(requiredWins,winsPlayer,winsAI);
if (winsPlayer == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "Player";
disabler()
createEndButton()
return;
}
if (winsAI == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "AI";
disabler()
createEndButton()
return;
}
}
}```

Your code seems to be pretty complicated. The state of the wins/required wins etc. is not saved adequately in it. For playing you add event listeners per game (click), which is pretty inefficient imho.
I have created a mockup (a minimal reproducable example) for the handling of games, using data attributes to remember the state of a game and event delegation for the handling. Maybe it's useful for you.
Not related, but here's my take on RPS.
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === `play`) {
return play(evt.target);
}
if (evt.target.name === `nWins`) {
return reset(evt.target);
}
}
function reset(radio) {
const value = radio === `none`
? Number.MAX_SAFE_INTEGER : +radio.value;
const bttn = document.querySelector(`#play`);
const result = document.querySelector(`#result`);
result.textContent = `(Re)start initiated, click [Play]`;
result.dataset.wins = bttn.dataset.wins = 0;
bttn.dataset.plays = 0;
return bttn.dataset.winsrequired = value;
}
function play(bttn) {
if (+bttn.dataset.winsrequired < 1) {
return document.querySelector(`#result`)
.textContent = `Select best of to start playing ...`;
}
const result = document.querySelector(`#result`);
bttn.dataset.plays = +bttn.dataset.plays + 1;
const won = Math.floor(Math.random() * 2);
const wins = +result.dataset.wins + won;
result.textContent = `${won ? `You win` : `You loose`} (plays: ${
bttn.dataset.plays}, wins ${wins})`;
result.dataset.wins = wins;
if (+bttn.dataset.plays === +bttn.dataset.winsrequired) {
result.textContent = `You won ${wins} of ${
bttn.dataset.winsrequired} games. Choose 'Best of'
to start another game`;
bttn.dataset.plays = bttn.dataset.winsrequired = 0;
result.dataset.wins = 0;
document.querySelectorAll(`[name="nWins"]`)
.forEach(r => r.checked = false);
}
}
Best of
<input type="radio" name="nWins" value="3"> 3
<input type="radio" name="nWins" value="5"> 5
<input type="radio" name="nWins" value="none"> indefinite
<button id="play" data-winsrequired="0" data-plays="0" >Play</button>
<p id="result" data-wins="0"></p>

Related

Counter App: Button function to trigger various if else messages

I'm building a passenger counter application for buses with vanilla javascript and I'm trying to wrap my head around how, when clicking a HTML DOM Object button, will alter the messages I want to output based on where the count is.
I have an increase and decrease button that increase or decrease the count by 1. Each bus has different passenger capacities, so I've placed each three busses in the navbar (dds, ddsb, mci). When clicking "dds" for example, I want specific messages to be called relative to where the count is. Likewise for other bus models.
let messageEl = document.getElementById("message-el")
let countEl = document.getElementById("count-el")
let ddsNavEl = document.getElementById("dds-nav-el")
let ddsbNavEl = document.getElementById("ddsb-nav-el")
let mciNavEl = document.getElementById("mci-nav-el")
let increaseEl = document.getElementById("increase-btn")
let decreaseEl = document.getElementById("decrease-btn")
let increaseFiveEl = document.getElementById("increaseFive-btn")
let decreaseFiveEl = document.getElementById("decreaseFive-btn")
var count = 0
/* BASIC COUNTER FUNCTIONALITY WITH NO SEATING LIMIT WARNINGS */
function increase() {
count++
countEl.textContent = count
}
function decrease() {
count--
countEl.textContent = count
}
function increaseFive() {
count += 5
countEl.textContent = count
}
function decreaseFive() {
count -= 5
countEl.textContent = count
}
function reset() {
messageEl.textContent = "";
countEl.textContent = 0
count = 0
ddsNavEl.style.fontWeight = "normal";
ddsbNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
/* COUNTER WITH SEATING AND STANDING LIMIT WARNINGS */
function ddsSelect() {
if (count === 15) {
message = "you are at full seating capacity"
} else if (count > 16) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
ddsNavEl.style.fontWeight = "bold";
ddsbNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
function ddsbSelect() {
if (count === 12) {
message = "you are at full seating capacity"
} else if (count > 13) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
ddsbNavEl.style.fontWeight = "bold";
ddsNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
function mciSelect() {
if (count === 10) {
message = "you are at full seating capacity"
} else if (count > 11) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
mciNavEl.style.fontWeight = "bold";
ddsNavEl.style.fontWeight = "normal";
ddsbNavEl.style.fontWeight = "normal";
}
I didn't include all of your functions in this example, but essentially I think the best way to do this would be to create an object and instantiate it per bus, either based on its type or id of some kind. You mentioned in your example that there were three types of bus... "dds, ddsb, and mci" but essentially by using this technique you could simply instantiate more instances of the object if you needed to setup another bus at some point in the future.
Example below, all of these functions could be setup to accept html elements to update various interface elements. None of that is included because none of it was provided.
let bus = {
passengers: 0,
increase: function() {
this.passengers++;
console.log(this.passengers);
},
decrease: function() {
this.passengers--;
console.log(this.passengers);
},
increaseFive: function() {
this.passengers += 5;
console.log(this.passengers);
},
decreaseFive: function() {
this.passengers -= 5;
console.log(this.passengers);
}
};
// bus types dds, ddsb, mci
let ddsBus = Object.create(bus);
ddsBus.increase();
ddsBus.increaseFive();
let ddsbBus = Object.create(bus);
ddsbBus.increase();
ddsbBus.increaseFive();
ddsbBus.increase();
let mciBus = Object.create(bus);
mciBus.increase();
mciBus.increaseFive();
mciBus.increase();
mciBus.increase();
console.log("dds : " + ddsBus.passengers); //expected value: 6
console.log("ddsb : " + ddsbBus.passengers); //expected value: 7
console.log("mci : " + mciBus.passengers); //expected value: 8

Subtract an image that is representing a life in a game

Im try to code a mini game.
The game has two boxes you can click on. The boxes are assigned a random number between 1 and 2.
When the game starts, you have 5 lives. These lives are represented as 5 pictures of a small human.
When the player gets 3,5 and 7 correct points you get a extra life. Which i have achieved.
Now im trying to subtract a life everytime the player clicks on the wrong box.
function setRandomNumber() {
randomNumber = Math.floor(Math.random() * 2 + 1);
if (randomNumber === 1) {
numberOfRightAnswersSpan.innerHTML = `${++correctNumber}`;
outputDiv.innerHTML = `Det er riktig svar.`;
if (correctNumber === 3 || correctNumber === 5 || correctNumber === 7) {
numberOfLivesDiv.innerHTML += `<img src="images/person1.jpg"/>`
}
} else {
numberOfWrongAnswersSpan.innerHTML = `${++wrongNumber}`;
outputDiv.innerHTML = `Det er feil svar.`;
}
}
I made a few changes to your code, but tried to keep it fairly similar to your original. I changed your template literals to strings. I changed your .innerHTML modifications to .innerText modifications. I refactored some whitespace to make your if statement more readable. Instead of adding the img element by appending the html string, I used the .appendChild method and createElement method to make the img elements. I also added a class to the element to make it easier to grab later.
function setRandomNumber() {
randomNumber = Math.floor(Math.random() * 2 + 1);
if (randomNumber === 1) {
numberOfRightAnswersSpan.innerText = ++correctNumber;
outputDiv.innerText = "Det er riktig svar.";
if (
correctNumber === 3 ||
correctNumber === 5 ||
correctNumber === 7
) {
const newLife = document.createElement("img");
newLife.src = "images/person1.jpg";
newLife.classList.add("life");
numberOfLivesDiv.appendChild(newLife);
}
} else {
numberOfWrongAnswersSpan.innerText = ++wrongNumber;
outputDiv.innerText = "Det er feil svar.";
const aLife = document.querySelector(".life");
aLife.remove();
}
}
It is important to note at this point there is not logic to check for how many life exists, or what to do when lives run out. Eventually you may hit an error because there is not element with a class of life.
I would re-render the lives every time the number of lives changes.
let number_of_lives = 5;
const lives_container = document.getElementById("user-lives");
function draw_lives(){
lives_container.innerHTML = "";
for(let i = 0; i < number_of_lives; i++){
const img = document.createElement("img");
img.setAttribute("alt", "life.png");
const new_life = img;
lives_container.appendChild(new_life);
};
if(number_of_lives <= 0) lives_container.innerText = number_of_lives;
};
function remove_life() {
number_of_lives--;
draw_lives();
};
function add_life() {
number_of_lives++;
draw_lives();
};
draw_lives();
#user-lives > * {
margin: 10px;
background: #7f7;
}
<div id="user-lives"></div>
<button onclick="add_life();">Add life</button>
<button onclick="remove_life();">Remove life</button>

How to prevent HTML button from clicking if already running JS

I am wondering how I might be able to stop a button clicking if the function it is performing is running. Here is my JS code:
let money = 0;
let running = false;
function start(time, val) {
if (running == false) {
running = true;
console.log(running)
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout("start(" + time + ")", 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
} else if (running == true) {
console.log("Already Growing!");
};
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
What it does is start a progress bar (progress div). I want the button to alert a message saying already going or something like that.
The issue I am having is that it is jumping to the else if statement, and not running anything. The odd thing is that if I add a console.log into the middle of the if statement it works.
I think it is because the bar takes time to fill, it will never reach full if the user clicks it, because it will jump to the else if statement and cancel out the if function. (It only becomes false again after the bar reaches 100%)
Can anyone help? I am open to JS or Jquery (bit rusty on that tho).
Thanks
You need to prevent the button clicking, not the actual start function that you need to call it from by the timer. So it's better to separate these functions:
let money = 0;
let running = false;
// when clicking the button
function onClickButton(time, val) {
if(running) {
console.log("Already Growing!");
} else {
running = true;
start(time, val);
}
}
// timer function
function start(time, val) {
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(() => start(time), 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
}
#moneyValue::before {
content: 'Money: ';
}
<div id="moneyValue">0</div>
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="onClickButton(0, this.id)">Plant Seed</button>
Break out the logic into another function that does the updating. Button that starts it on one method and the logic that updates the UI in another.
let money = 0;
let running = false;
function start(time, val) {
if (running == false) {
running = true;
console.log(running)
runIt(time, val);
} else if (running == true) {
console.log("Already Growing!");
};
}
function runIt(time, val) {
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(function () {runIt(time); }, 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
running = false;
}
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
<div id="moneyValue"></div>
You could add an additional parameter that tells the function that the call is coming from the loop, and doesn't need to check if it's already running.
let money = 0;
let running = false;
function start(time, val, isFromTimer) {
if (running == false || isFromTimer == true) { // add check
running = true;
console.log(running)
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(() => start(time, val, true), 30); // tell function it's from the timer
if (time >= 100) { // use more than or equal to instead
bar.value = 0;
let id = val;
money++;
//document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
} else if (running == true) {
console.log("Already Growing!");
};
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
Why don't you just use some CSS manipulation in your function once it is clicked?
document.getElementById('restart-button').disabled = true;
Then at the end of your function:
document.getElementById('restart-button').disabled = false;

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Can't Get Variable to Add Properly

I have a variable++; in an if/else statement (it being in the else part). It's supposed to add 1 to a score of how many wrong guesses one has.
For some reason it never adds just one, it will also add numbers ranging from 3 to 7 whenever I submit a 'guess'. Can you guys tell me if I'm looping wrong or something? Please try to explain in detail.
EDIT: I realized part of the problem. The tries++; is actually looping once for each letter [var]choice didn't match or equal. For instance if I enter "a" for "apple" tries++; will loop four times because of the four other characters. So how do I get it to only loop only once instead of adding one for each missed character?
This is my code.
// JavaScript Document
var words = new Array("apple","orange","banana","lime","mango","lemon","avacado","pineapple","kiwi","plum","watermelon","peach");
var randomNum;
var word;
var tries = 0;
$('#guess').prop('disabled', true);
$(function(){
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = "";
randomNum = Math.floor(Math.random() * words.length)
for (var i =0; i < words[randomNum].length; i++) {
word += "*";
}
console.log(words[randomNum]);
$('#word').html(word);
});
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase();
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
}
if (words[randomNum].charAt(i) !== choice) {
tries++;
}
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7)
$('#tries').html("YOU LOSE");
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
});
Got it working!
The issue is related to the tries variable, inside the for loop (per letter). In order to see the odd behavior add a console.log(tries); in your code, inside the loop and you will see. At first time it will increase in 1 then the value will change completely (I will suggest some debugging here to understand what's going on with more accuracy since I did this real quick). The solution is increasing the variable out of the for loop context to make it work (I did this in the provided example from the bottom).
By the way, it seems that you are trying to implement a "Hangman" game and to be honest, when implementing those things you need to be really organized.
I fixed your issue, improved the code a lot and also considered other possible game scenarios like:
Play Again
Game Over
Win
Go Back
Please take a look. Just to know, HTML and CSS are just improvisations made for this example, some improvements are needed so just take them as a reference.
Update: What you had put in the EDIT part from your post is correct.
You can run this script at the bottom.
// Game variables
var GAME_WORDS = [ // List of words available when playing
'apple',
'orange',
'banana',
'lime',
'mango',
'lemon',
'avacado',
'pineapple',
'kiwi',
'plum',
'watermelon',
'peach'
],
GAME_MASKED_WORD = '', // Stores the masked word to be discovered
GAME_SELECTED_WORD = '', // Stores the readable word
GAME_PLAYER_ATTEMPTS = 0, // Stores player attempts when failing
GAME_RANDOM_NUMBER = 0, // Random number to pick a word
GAME_MAX_ATTEMPTS = 7, // Max. player attempts before a game over
GAME_UI_COMPONENTS = { // UI components declaration
start: $('#start'),
reset: $('#reset'),
back: $('#back'),
guess: $('#guess'),
msg: $('#msg'),
word: $('#word'),
letter: $('#letter')
},
GAME_UI_SECTIONS = { // UI sections declaration
menu: $('#menu'),
game: $('#game')
};
$(function() {;
var ui = GAME_UI_COMPONENTS;
// Initialize game
init();
// Start button handler
ui.start.on('click', function(e) {
start();
});
// Guess button handler
ui.guess.on('click', function(e) {
guess();
});
// Play Again button handler
ui.reset.on('click', function(e) {
reset();
start();
});
// Go Back button handler
ui.back.on('click', function(e) {
init();
});
});
/**
* Used to initialize the game for first time
*/
function init() {
var sections = GAME_UI_SECTIONS;
sections.menu.show();
sections.game.hide();
reset();
};
/**
* Used to start the game
*/
function start() {
var ui = GAME_UI_COMPONENTS,
sections = GAME_UI_SECTIONS,
words = GAME_WORDS;
sections.menu.hide();
sections.game.show();
GAME_RANDOM_NUMBER = Math.floor(Math.random() * words.length);
for (var i = 0; i < words[GAME_RANDOM_NUMBER].length; ++i) {
GAME_MASKED_WORD += '*';
}
GAME_SELECTED_WORD = words[GAME_RANDOM_NUMBER];
ui.word.html(GAME_MASKED_WORD);
ui.letter.focus();
};
/**
* Guess button handler
*/
function guess() {
var ui = GAME_UI_COMPONENTS,
words = GAME_WORDS,
matches = false,
choice;
// Clean messages each time player do a guess
showMsg('');
if (ui.letter && ui.letter.val()) {
choice = $.trim(ui.letter.val().toLowerCase());
}
if (choice) {
for (var i = 0; i < GAME_MASKED_WORD.length; ++i) {
if (words[GAME_RANDOM_NUMBER].charAt(i) === choice) {
GAME_MASKED_WORD = GAME_MASKED_WORD.substr(0, i) + choice +
GAME_MASKED_WORD.substr(i + 1);
matches = true;
}
}
if (!matches) {
++GAME_PLAYER_ATTEMPTS;
}
} else {
showMsg('Please type a letter.');
}
// Show attempts left if more than zero
if (GAME_PLAYER_ATTEMPTS > 0) {
showMsg('You have ' +
(GAME_MAX_ATTEMPTS - GAME_PLAYER_ATTEMPTS) +
' attempt(s) left.');
}
// Check game status each time doing a guess
if (isGameOver()) {
lose();
} else if (isGameWin()) {
win();
} else {
ui.word.html(GAME_MASKED_WORD);
}
ui.letter.focus();
};
/**
* Used to set all game variables from the scratch
*/
function reset() {
var ui = GAME_UI_COMPONENTS;
GAME_MASKED_WORD = '';
GAME_PLAYER_ATTEMPTS = 0;
GAME_RANDOM_NUMBER = 0;
showMsg('');
ui.guess.show();
ui.letter.val('');
ui.word.html('');
};
/**
* Handler when player lose the game
*/
function lose() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Lose!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Handler when player win the game
*/
function win() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Win!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Use to print UI messages for the player
*/
function showMsg(msg) {
var ui = GAME_UI_COMPONENTS;
ui.msg.html(msg);
};
/**
* Check game status, if player is going to lose the game
* #returns Boolean
*/
function isGameOver() {
return (GAME_PLAYER_ATTEMPTS >= GAME_MAX_ATTEMPTS);
};
/**
* Check game status, if player is going to win the game
* #returns Boolean
*/
function isGameWin() {
return (GAME_MASKED_WORD === GAME_SELECTED_WORD);
};
.btn {
cursor: pointer;
}
span#msg {
color: red;
font-weight: bold;
}
.text {
font-size: 3em;
}
input#letter {
width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
<div id="menu">
<span class="text">Hangman!</span>
<br><br>
<img src="http://img3.wikia.nocookie.net/__cb20130207191137/scribblenauts/images/0/01/Hangman.png" height="200" width="120"/>
<br><br>
<input type="button" class="btn" id="start" value="Start Game"/>
</div>
<div id="game">
<span id="msg"></span>
<br><br>
Letter: <input type="text" id="letter" value="" maxlength="1"/>
<br><br>
<input type="button" class="btn" id="guess" value="Guess"/>
<input type="button" class="btn" id="reset" value="Play Again"/>
<input type="button" class="btn" id="back" value="Go Back"/>
<br><br>
Word: <div id="word" class="text"></div>
</div>
</div>
Hope this helps.
try this one:
Modify guess click handler like this:
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase(),
found = false;
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
found = true
}
}
if(!found){
tries++;
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7){
$('#tries').html("YOU LOSE");
}
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
Also on start reset the tries:
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = ""; tries = 0;

Categories