Codecademy javascript Number guesser problem - javascript

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.

Related

useState in while cause infinite loop

I trying to make Blackjack game in React. A bot has got 2 cards at start. If user stands, and bots card value is less than 17, it should draw addictional card, but then program cause infinite loop. This is my code:
const [playerCards, setPlayerCards] = useState<Card[]>([]);
const shuffledDeck = shuffleDeck(deck);
const [dealerCards, setDealerCards] = useState<Card[]>([]);
const shuffleDeck = (deck: Card[]): Card[] => {
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
};
const handleStand = () => {
if (gameState === 'playing') {
console.log(shuffledDeck[playerCards.length + dealerCards.length]);
while(getHandValue(dealerCards) < 17) {
setDealerCards([
...dealerCards,
shuffledDeck[playerCards.length + dealerCards.length],
]);
}
}
let dealerHandValue = getHandValue(dealerCards);
const playerHandValue = getHandValue(playerCards);
if (dealerHandValue > 21 || dealerHandValue < playerHandValue) {
setGameState('won');
setPlayerBalance(playerBalance + currentBet);
} else if (dealerHandValue > playerHandValue) {
setGameState('lost');
setPlayerBalance(playerBalance - currentBet);
} else {
setGameState('tied');
}
};
const getHandValue = (cards: Card[]): number => {
let value = 0;
let numAces = 0;
for (const card of cards) {
if (card.rank === Rank.Ace) {
numAces++;
} else if (card.rank === 'J' || card.rank === 'K' || card.rank === 'Q') {
value += 10;
} else {
value += Number(card.rank);
}
}
while (numAces > 0) {
if (value + 11 > 21) {
value += 1;
} else {
value += 11;
}
numAces--;
}
return value;
};
The goal is to make bot draw a cards until value of his cards will be at least 17.
As discussed in the comments, using setDealerCards inside the while loop can be problematic. Setting the state causes a re-render to the component and may trigger the function again depending on it's use.
Another problem may be that since React schedules it's updates you may not get the most updated state every time you set the state again in the while loop.
So this might help
const handleStand = () => {
let newDealerCards = [...dealerCards];
if (gameState === 'playing') {
while(getHandValue(newDealerCards) < 17) {
newDealerCards =
[...newDealerCards, shuffledDeck[playerCards.length + newDealerCards.length]];
}
setDealerCards(newDealerCards);
}
let dealerHandValue = getHandValue(newDealerCards);
const playerHandValue = getHandValue(playerCards);
if (dealerHandValue > 21 || dealerHandValue < playerHandValue) {
setGameState('won');
setPlayerBalance(playerBalance + currentBet);
} else if (dealerHandValue > playerHandValue) {
setGameState('lost');
setPlayerBalance(playerBalance - currentBet);
} else {
setGameState('tied');
}
};
We make the new newDealerCards variable to spread dealerCards state, we then do the while loop with your condition and update newDealerCards accordingly. When we're done, only then we set the state again with the updated variable we made and thus we avoid calling setDealerCards multiple times inside the while loop.

(Codility binary gap error) Problem : Cant convert octal code into expected array

Its works well when converting to string except binary with prefix 0.
My code:
function dec2bin(dec) {
return dec.toString(2);
}
function getRndInteger(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
const min = 1;
const max = 2147483647;
const nilai = dec2bin(getRndInteger(min, max));
function solution(N) {
**const nilaiArr = Array.from(String(N), Number);**
let temporer = 0;
let save = \[\];
for (let i = 0; i \< nilaiArr.length - 1; i++) {
if (nilaiArr\[i\] == 1 && nilaiArr\[i + 1\] == 0) {
for (let j = i + 1; nilaiArr\[j\] == 0; j++) {
temporer++;
if (nilaiArr\[j + 1\] == 1) {
save.push(temporer);
temporer = 0;
} else if (nilaiArr\[j + 1\] == undefined) {
break;
}
}
} else {
continue;
}
}
if (save.length === 0) {
console.log(0);
} else {
save.sort();
save.reverse();
console.log(save\[0\]);
}
}
solution(nilai);
Problem sample : 010000010001 became 1073745921.
Expected output same as origin binary number. I cant find the answer as long as I scroll in this forum lol. I

Reuse button to trigger another function

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;
}

How can I get setInterval() to increase by 1 instead of 12?

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()

refactoring: How can I improve this as a clean code

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.

Categories