Review Algorithmic Thinking by Building a Dice Game - Step 13

Tell us what’s happening:

Hey fCC Gang, I have been working on this problem for a few hours now. After I implemented the logic for the full house, I was instructed to update the radio button options in the hint tab, so I called the updateRadioButtons function with the correct paremeters but the code didn’t pass so I manually updated the radio options, but still the code does not submit.

Can Anyone Help?

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

const detectFullHouse = (listOfAllDice) => {
    
    // Sort the array in descending order (highest to lowest)
    const sortedArr = listOfAllDice.sort((num1, num2) => num2 - num1);

    // Find unique values from the sorted array
    const uniqueValues = [];
    for (const num of sortedArr) {
        if (!uniqueValues.includes(num)) {
            uniqueValues.push(num); // Add the number to uniqueValues if it’s not already there
        }
    }

    // Count occurrences of each unique value in the sorted array
    const counts = [];
    for (const num of uniqueValues) {
        const count = sortedArr.filter(die => die === num).length; // Count how many times the current unique value appears
        counts.push(count); // Store the count in the counts array
    }

    // Ensure there are exactly two unique values
    if (uniqueValues.length !== 2) {
        return false; // If there aren't exactly two unique values, it can't be a full house
    }

    // A full house is valid if one value appears 3 times and the other appears 2 times
    if ((counts[0] === 3 && counts[1] === 2) || (counts[0] === 2 && counts[1] === 3)) {
        const fullHouseInput = document.querySelector('#full-house');
        const fullHouseLabel = document.querySelector('#full-house span');
        const none = document.querySelector('#none');
        const allRadioInputs = document.querySelectorAll('input[name="score-options"]');

        allRadioInputs.forEach((radio, index) => {
            if (index !== 2 && index !== 5) { // If the index is not 2 or 5 (FH or none), disable them!
                radio.disabled = true;
                radio.checked = false;
            }
        });

 // updateRadioOptions(2, 25, allRadioInputs);   // Enable and check "Full House" radio button, disable rest
        fullHouseInput.disabled = false; // Enabled Third Radio Button
        fullHouseInput.checked = true; // Marks radio button as a selected option
        fullHouseInput.value = 25; // Set Input Value to 25
        scoreSpans[2].innerHTML = ", score = 25"; // Set third span text to ", score = 25"
        return true; // Full house detected

    } else {
        // Always update "None of the above" option
        none.disabled = false;
        none.checked = true;
        none.value = 0;
        scoreSpans[5].innerHTML = ", score = 0";
    }

    // No full house found
    return false;
};

const resetRadioOptions = () => {
  scoreInputs.forEach((input) => {
    input.disabled = true;
    input.checked = false;
  });

  scoreSpans.forEach((span) => {
    span.textContent = "";
  });
};

const resetGame = () => {
  diceValuesArr = [0, 0, 0, 0, 0];
  score = 0;
  round = 1;
  rolls = 0;

  listOfAllDice.forEach((dice, index) => {
    dice.textContent = diceValuesArr[index];
  });

  totalScoreElement.textContent = score;
  scoreHistory.innerHTML = "";

  rollsElement.textContent = rolls;
  roundElement.textContent = round;

  resetRadioOptions();
};

rollDiceBtn.addEventListener("click", () => {
  if (rolls === 3) {
    alert("You have made three rolls this round. Please select a score.");
  } else {
    rolls++;
    resetRadioOptions();
    rollDice();
    updateStats();
    getHighestDuplicates(diceValuesArr);
  
  }
});

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36

Challenge Information:

Review Algorithmic Thinking by Building a Dice Game - Step 13

Call your detectFullHouse function within the above event listener callback function.

Doesn’t work :frowning:

rollDiceBtn.addEventListener("click", () => {
  if (rolls === 3) {
    alert("You have made three rolls this round. Please select a score.");
  } else {
    rolls++;
    resetRadioOptions();
    rollDice();
    updateStats();
    getHighestDuplicates(diceValuesArr);
    detectFullHouse(listOfAllDice);

  }
});

Hint:

When a full house is not rolled, your detectFullHouse function should enable the final radio button, set its value to 0 , and set the final span to display the text , score = 0 .

why are you not using updateRadioOption?

Also, console.log what you’re passing to detectFullHouse().

I tried calling this function first with arguments, but the code wasn’t passing so I thought it wanted me to set it manually.

// updateRadioOptions(2, 25, allRadioInputs);   // Enable and check "Full House" radio button, disable rest

Hi @PieroGentile

From the Pyramid Generator practice project console.log()

Happy coding

Hey Teller, I know about console.log, I have linked a screenshot

1 Like

Tried calling updateRadioOptions again and it doesn’t work

 // A full house is valid if one value appears 3 times and the other appears 2 times
    if ((counts[0] === 3 && counts[1] === 2) || (counts[0] === 2 && counts[1] === 3)) {
        const fullHouseInput = document.querySelector('#full-house');
        const fullHouseLabel = document.querySelector('#full-house span');
        const none = document.querySelector('#none');
        const allRadioInputs = document.querySelectorAll('input[name="score-options"]');

        allRadioInputs.forEach((radio, index) => {
            if (index !== 2 && index !== 5) { // If the index is not 2 or 5 (FH or none), disable them!
                radio.disabled = true;
                radio.checked = false;
            }
        });

        updateRadioOptions(2, 25, false, true); // Enable and check "Full House" radio button, disable rest
        scoreSpans[2].innerHTML = ", score = 25"; // Set third span text to ", score = 25"
        return true; // Full house detected

    } else {
        updateRadioOptions(5, 0, false, true);
        scoreSpans[5].innerHTML = ", score = 0";
    }

please check on where updateRadioOptions is defined, are you using it correctly?

Try entering console.log(diceValuesArr, listOfAllDice) just before the call to getHighestDuplicates() in the event handler, then click the “Console” tab next to the “Preview” tab to see the comparison.

Currently, your detectFullHouse() function is throwing an error on the first line of code, which you should be able to see in the “Console” tab, too.

Hi, thanks for trying to help me - I added console.log(diceValuesArr, listOfAllDice) just before the call to the getHighestDuplicates() call in the rolldiceBtn event listener. Here’s the results from the console.log

Here is the full code if anyone wants to try help me debug it

const listOfAllDice = document.querySelectorAll(".die");
const scoreInputs = document.querySelectorAll("#score-options input");
const scoreSpans = document.querySelectorAll("#score-options span");
const roundElement = document.getElementById("current-round");
const rollsElement = document.getElementById("current-round-rolls");
const totalScoreElement = document.getElementById("total-score");
const scoreHistory = document.getElementById("score-history");
const rollDiceBtn = document.getElementById("roll-dice-btn");
const keepScoreBtn = document.getElementById("keep-score-btn");
const rulesContainer = document.querySelector(".rules-container");
const rulesBtn = document.getElementById("rules-btn");

let diceValuesArr = [];
let isModalShowing = false;
let score = 0;
let round = 1;
let rolls = 0;

const rollDice = () => {
  diceValuesArr = [];

  for (let i = 0; i < 5; i++) {
    const randomDice = Math.floor(Math.random() * 6) + 1;
    diceValuesArr.push(randomDice);
  };

  listOfAllDice.forEach((dice, index) => {
    dice.textContent = diceValuesArr[index];
  });
};

const updateStats = () => {
  rollsElement.textContent = rolls;
  roundElement.textContent = round;
};

const updateRadioOption = (index, score) => {
  scoreInputs[index].disabled = false;
  scoreInputs[index].value = score;
  scoreSpans[index].textContent = `, score = ${score}`;
};

const updateScore = (selectedValue, achieved) => {
  score += parseInt(selectedValue);
  totalScoreElement.textContent = score;

  scoreHistory.innerHTML += `<li>${achieved} : ${selectedValue}</li>`;
};

const getHighestDuplicates = (arr) => {
  const counts = {};

  for (const num of arr) {
    if (counts[num]) {
      counts[num]++;
    } else {
      counts[num] = 1;
    }
  }

  let highestCount = 0;

  for (const num of arr) {
    const count = counts[num];
    if (count >= 3 && count > highestCount) {
      highestCount = count;
    }
    if (count >= 4 && count > highestCount) {
      highestCount = count;
    }
  }

  const sumOfAllDice = arr.reduce((a, b) => a + b, 0);

  if (highestCount >= 4) {
    updateRadioOption(1, sumOfAllDice);
  }

  if (highestCount >= 3) {
    updateRadioOption(0, sumOfAllDice);
  }

  updateRadioOption(5, 0);
};

const detectFullHouse = (listOfAllDice) => {

    // Sort the array in descending order (highest to lowest)
    const sortedArr = listOfAllDice.sort((num1, num2) => num2 - num1);

    // Find unique values from the sorted array
    const uniqueValues = [];
    for (const num of sortedArr) {
        if (!uniqueValues.includes(num)) {
            uniqueValues.push(num); // Add the number to uniqueValues if it’s not already there
        }
    }

    // Count occurrences of each unique value in the sorted array
    const counts = [];
    for (const num of uniqueValues) {
        const count = sortedArr.filter(die => die === num).length; // Count how many times the current unique value appears
        counts.push(count); // Store the count in the counts array
    }

    // Ensure there are exactly two unique values
    if (uniqueValues.length !== 2) {
        return false; // If there aren't exactly two unique values, it can't be a full house
    }

    // A full house is valid if one value appears 3 times and the other appears 2 times
    if ((counts[0] === 3 && counts[1] === 2) || (counts[0] === 2 && counts[1] === 3)) {
        const fullHouseInput = document.querySelector('#full-house');
        const fullHouseLabel = document.querySelector('#full-house span');
        const none = document.querySelector('#none');
        const allRadioInputs = document.querySelectorAll('input[name="score-options"]');

        allRadioInputs.forEach((radio, index) => {
            if (index !== 2 && index !== 5) { // If the index is not 2 or 5 (FH or none), disable them!
                radio.disabled = true;
                radio.checked = false;
            }
        });

        updateRadioOption(2, 25, false, true); // Enable and check "Full House" radio button, disable rest
        scoreSpans[2].innerHTML = ", score = 25"; // Set third span text to ", score = 25"
        return true; // Full house detected

    } else {
        updateRadioOption(5, 0, false, true);

        scoreSpans[5].innerHTML = ", score = 0";
    }

    // No full house found
    return false;
};


const resetRadioOptions = () => {
  scoreInputs.forEach((input) => {
    input.disabled = true;
    input.checked = false;
  });

  scoreSpans.forEach((span) => {
    span.textContent = "";
  });
};

const resetGame = () => {
  diceValuesArr = [0, 0, 0, 0, 0];
  score = 0;
  round = 1;
  rolls = 0;

  listOfAllDice.forEach((dice, index) => {
    dice.textContent = diceValuesArr[index];
  });

  totalScoreElement.textContent = score;
  scoreHistory.innerHTML = "";

  rollsElement.textContent = rolls;
  roundElement.textContent = round;

  resetRadioOptions();
};

rollDiceBtn.addEventListener("click", () => {
  if (rolls === 3) {
    alert("You have made three rolls this round. Please select a score.");
  } else {
    rolls++;
    resetRadioOptions();
    rollDice();
    updateStats();
    console.log(diceValuesArr, listOfAllDice);
    getHighestDuplicates(diceValuesArr);
  
  }
});

rulesBtn.addEventListener("click", () => {
  isModalShowing = !isModalShowing;

  if (isModalShowing) {
    rulesBtn.textContent = "Hide rules";
    rulesContainer.style.display = "block";
  } else {
    rulesBtn.textContent = "Show rules";
    rulesContainer.style.display = "none";
  }
});

keepScoreBtn.addEventListener("click", () => {
  let selectedValue;
  let achieved;

  for (const radioButton of scoreInputs) {
    if (radioButton.checked) {
      selectedValue = radioButton.value;
      achieved = radioButton.id;
      break;
    }
  }

  if (selectedValue) {
    rolls = 0;
    round++;
    updateStats();
    resetRadioOptions();
    updateScore(selectedValue, achieved);
    if (round > 6) {
      setTimeout(() => {
        alert(`Game Over! Your total score is ${score}`);
        resetGame();
      }, 500);
    }
  } else {
    alert("Please select an option or roll the dice");
  }
});

changed it to updateRadioOption and still doesnt work

The reference error is telling you there is no function named updateRadioOptions. Find that function in the code, examine it to make sure you understand what it does, look at how it was used in getHighestDuplicates(). Notice how many parameters should be passed to that function. That’s not the same number of parameters you are passing in when you use it. @ILM was trying to get you to pay attention to that, but the code you posted shows you’re still using it incorrectly.

Your console log is also showing you that diceValuesArr is an array, but listOfAllDice is not an array, hence your detectFullHouse function breaks on the very first line when you attempt a sort.

I suggest you keep your console open and console.log frequently as you build a function to test it. Baby steps. Write one line. Test. Write another line. Test. IMHO, learning how to test your code is the most important thing to know when you’re coding.

Also, if you still need help, please send ALL of your updated JS code to help us understand why you got the console output you sent @Teller.

Hey brother, I got home from church and spent 2 hours removing code & implementing new concepts along with debugging the code from scratch using JSfiddle, and it finally passed!

It was chaos debugging everything but I was determined to not quit, and it got solved in the end!

Thank you to everyone who tried helping me out.

Edit: Regarding updateRadioOption… this was one of the problems out of many that were causing the errors. When I seen @ILM’s comment I changed each instance of updateRadioOptions to updateRadioOption but it didn’t work. I also called the detectFullHouse function inside the rollDiceBtn function but still no hope. I ended up re-coding it & copying snippets of code to JSFiddle to debug everything, and it worked!

Now it’s time to write my research paper regarding what I learned during that task!

1 Like