So I'm still practicing and learning and I'm creating a number guessing game and I was planning on re-using a existing button to trigger the reset of the game however for some reason it will reset however upon doing so-- resetGame() will reset variables but not start the checkGuess() like it's suppose to and only continue to randomize the randomNumber when 'submit' button is clicked..
I'm assuming that this must be bad practice and figure I shouldn't do this but wanted to ask why this wasn't re-starting the game as it should... what am I missing?
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
enterButton.addEventListener('click', checkGuess);
// function log() {
// console.log(Number(document.getElementById('guessField').value));
// }
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
enterButton.addEventListener('click', resetGame);
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
// document.getElementById('userGuess').value = '';
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
}
The problem is that after you finish the game the resetGame callback is added as event listener and is triggered every time you click the userSubmit button. There are few possibilities how to solve this problem:
1. Check if the game is running
In this solution, you don't add the resetGame callback, but you call it within the checkGuess callback. To make this solution work you have to add a variable which represents if the game is running or not. This way if the game is still running the checkGuess callback will call the default behaviour, but after the gameOver is called, checkGuess will reset the game.
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
let isRunning = true;
enterButton.addEventListener('click', checkGuess);
function checkGuess() {
if (isRunning) { // Check if the game is running
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
} else {
resetGame();
}
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
isRunning = false;
// enterButton.addEventListener('click', resetGame); Move this line to the beggining
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
isRunning = true;
}
2. Remove the resetGame callback after reseting
Here you just remove the resetGame callback after it is called. First you add the resetGame (just like you have it now) after the game is finished, but remove the checkGuess as well so it doesn't trigger your logic. Next you remove the resetGame and add the guessCheck callbacks after the resetGame is called (you can see two lines at the end of resetGame function).
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
enterButton.addEventListener('click', checkGuess);
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
enterButton.removeEventListener('click', checkGuess); // Remove checkGuess and add resetGame
enterButton.addEventListener('click', resetGame);
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
enterButton.removeEventListener('click', resetGame); // Remove resetGame and add checkGuess
enterButton.addEventListener('click', checkGuess);
}
How about a slightly improved approach?
You define a boolean variable named gameIsOver. When the game is over, you set the value to true and when you reset, set the value to false.
Then you update your enterButton's click event listener. If game is over, you call the resetGame() function, else you call checkGuess function.
let gameIsOver = false; // keep track if the game is over, initially its false
enterButton.addEventListener("click", function (e) {
if (gameIsOver) {
resetGame();
} else {
checkGuess();
}
});
function gameOver() {
/* your existing code */
gameIsOver = true;
}
function resetGame() {
/* your existing code */
gameIsOver = false;
}
Related
My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()
So I am working on this project in codecademy that is a number guessing game. I am running into a bit of a kink. When the updateScore function fires, it says undefined. What it should do is update the humanScore variable or the computerScore variable based on the results of compareGuesses. When I put in the value of 'human' it says undefined when it should start adding up from zero. So the first time it is clicked it should be 1 and the second time should be 2 and so on. What am I forgetting or doing wrong?
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
// Write your code below:
function generateTarget() {
return Math.floor(Math.random() * 10);
};
function compareGuesses(humanGuess, computerGuess, generateTarget) {
let humanValue = Math.abs(humanGuess - generateTarget);
let computerValue = Math.abs (computerGuess - generateTarget);
if (humanValue < computerValue) {
return 'human';
} else if (humanValue === computerValue) {
return 'human';
} else {
return 'computer';
}
};
function updateScore(compareGuesses) {
if (compareGuesses === 'human') {
humanScore = humanScore + 1;
} else if (compareGuesses === 'computer') {
computerScore = computerScore + 1;
}
};
console.log(updateScore('human'));
You are passing functions as arguments to other functions and then treating them as a variable.
Here's an updated code:
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
// Write your code below:
function generateTarget() {
return Math.floor(Math.random() * 10);
};
function compareGuesses(humanGuess, computerGuess /*, generateTarget */) {
let generatedTarget = generateTarget(); // notice the "d"
let humanValue = Math.abs(humanGuess - generatedTarget);
let computerValue = Math.abs (computerGuess - generatedTarget);
if (humanValue <= computerValue) {
return 'human';
}
/* else if (humanValue === computerValue) {
return 'human';
} */
else {
return 'computer';
}
};
function updateScore(player) {
if (player === 'human') {
humanScore++; // = humanScore + 1;
}
else /* if (player === 'computer') */ {
computerScore++; // = computerScore + 1;
}
return "Round "+(currentRoundNumber++)+"\n"+
"Human: "+humanScore+"\n"+
"Computer: "+computerScore;
};
console.log(updateScore('human'));
You still need to fill-in the rest of the logic of the game.
I am currently studying JS myself.And make the pig-game which is project of the course that I watched. I'm always curious how can I improve my code but I got no idea where do I begin.
Is there some principle that I can improve any code?
If there's a way, Could you let me know? Thanks!
https://github.com/wonkooklee/pig-game
result : https://wonkooklee.github.io/pig-game/
below is main functions
document.querySelector('.btn-roll').addEventListener('click', function() {
if (gamePlaying) {
dice = Math.floor(Math.random() * 6) + 1;
diceDOM.style.display = 'block';
diceDOM.src = `dice-${dice}.png`;
if (dice === 6 && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
} else if (dice !== 1 && dice !== 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = 0;
} else if (dice === 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = dice;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (isNaN(input) === false) {
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
Martin Fowler wrote a great book "Refactoring". Besides, Fowler has a great blog Refactoring.com, where you can find a lot of information about refactoring with examples in Javascript.
I'm not strong in Javascript, but can let you some advices about your code.
1.Simplify Conditional Logic
For example like this:
if (dice === 6 && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
if (dice !== 1 && dice !== 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = 0;
return;
}
if (dice === 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = dice;
return;
}
nextPlayer();
2.Delete duplicated code and extract function
For example
function someFunctionName(diffRoundScore, lastDiceValue){
roundScore += diffRoundScore;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = lastDiceValue;
}
if (dice !== 1 && dice !== 6) {
someFunctionName(dice, 0);
return;
}
if (dice === 6) {
someFunctionName(dice, dice);
return;
}
3.Change check "dice for 6" to function
function isDiceEqualsSix { return dice === 6};
if (isDiceEqualsSix && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
if (dice !== 1 && !isDiceEqualsSix) {
someFunctionName(dice, 0);
return;
}
if (isDiceEqualsSix) {
someFunctionName(dice, dice);
return;
}
4.Change "6" to a constant variable or a function
const LIMIT_SCORE = 6;
function isDiceEqualsSix { return dice === LIMIT_SCORE};
if (isDiceEqualsSix && lastDice === LIMIT_SCORE) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
I hope I helped you.
I'm recently watching JavaScript online course, and I built the 'pig-game'.
There's input box for set the winning score.
I want to improve it if user types the value that is not 'number', then it's value will change automatically to '100' as default.
I put if statement there, but I can't solve It's parameter.
e.g. if(input === number) doesn't work.
You can check my github (https://github.com/wonkooklee/pig-game)
and code is below
//
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (input === number) { // This is that I'm dealing with
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
Here is what you want (if what you want is to check if an input has been enter by the user the value will not be "" (which would be falsy), so the test if(input) will be true):
document.querySelector('.btn-hold').addEventListener('click', function () {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (input) {
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}