Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task?

The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum of the dice rolls should always be displayed on the page. If a number 6 is rolled, the program should ignore it in the sum and instead throw two new dice, along with showing an error message indicating this situation.

Once all the dice rolls are completed, the total sum and the number of times the dice were thrown should be displayed. I've made progress with the code so far, but I'm unsure about handling the number 6 and if my approach is correct. Can you provide any insight or suggestions?

JavaScript Code

function rollDice() {
  var numDice = document.getElementById("diceNum").value;
  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
  };

  var x, text;
  x = document.getElementById("diceNum").value;

  if (isNaN(x) || x < 1 || x > 5) {
    window.alert('Input not valid');
    document.getElementById("dieContainer").style.display = "none";
  } else {
    document.getElementById("dieContainer").style.display = "block";
  }
};

Update:

let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
        console.log("You got a 6 and two new dices were thrown");
        document.getElementById("msg").innerHTML = "You got a 6 and two new dices were thrown";
    } else {
        sum += diceRoll;
        console.log(sum);
        document.getElementById("msg").innerHTML = "Result: " + sum;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}

I have successfully displayed the results, but now I am wondering if there is a way to prevent them from resetting every time the function is used. Any advice on persisting the results?

Answer №1

Modify the loop from for to while:

let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
    } else {
        sum += diceRoll;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}

Answer №2

Here is an example of how you could achieve this:

function rollDice() {
  var numDice = Number(document.getElementById("diceNum").value);
  if (isNaN(numDice) || numDice < 1 || numDice > 5) {
    window.alert('Input not valid');
    return
  }

  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  var total = 0

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    if(diceRoll === 6) {
      //Increase the maximum by 1 (because ignore 6: -1; add two: +2)
      numDice++
      //Decrease the current by 1 (to ignore the 6)
      i--
      continue
    }
    total += diceRoll
  };
  document.getElementById("diceTotal").innerText = total
  document.getElementById("diceCount").innerText = numDice
}
<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

Modifying Image on Tab Click using jQuery

In my current WordPress project, I am working on dynamically changing an image based on the tab that is clicked. I would like to use jQuery's fade effect to smoothly replace the image with a new one that is relative to the specific tab being clicked. ...

Using JSON.parse in Node.js to manipulate arrays with Javascript

While taking an online course, I came across a confusing code snippet: notes = JSON.parse(notesString). The confusion arises from the fact that this code is supposed to result in an object, but it's being treated as an array. Isn't JSON.parse sup ...

Use the regex tag in a React component to find a specific tag by name within two different possible

Looking for a regex that can identify <Field ...name="document"> or <FieldArray ...name="document"> within a multiline text string so they can be replaced with an empty string. The text string is not formatted as HTML or XHTML, it simply conta ...

Tips for preventing a span from disappearing when a hidden div is displayed during onmouseover

, there is a concern about the disappearing behavior of the span with ID "topnavbar" when the display property changes from none to block on a hidden div using onmouseover event. The query is how to ensure that the span remains visible at all times. Additi ...

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

Tips for retrieving and transforming the date time picker into the server format (toISOString)

I am attempting to utilize a datetime picker and convert it for server-side transmission, but I'm encountering issues. Here is my attempted code: <html> <head> <meta charset="utf-8"> <meta name="viewport" cont ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Using i18next to alter language in a React app

Implementing the i18next translation system into my React app was a breeze thanks to a helpful guide I found. However, I'm facing an issue with changing the language manually. The guide covered the setup process perfectly, but lacked information on ho ...

Difficulty in constructing an array from several Firebase Storage URLs

I'm attempting to retrieve multiple image URLs and store them in an array using Firebase Storage. However, I am facing issues accessing specific index positions within the testArray: var testArray = [] listAll(ref).then((res) => { res.item ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

When utilizing a wrapped v-text-field, it triggers warning messages and fails to update the data properly

Recently delving into the world of vue.js, I've been experimenting with creating a form using Vue, vuetify, and vuelidate. Oddly enough, when I don't wrap the v-text-field there are no issues, but as soon as I try to encapsulate it within compone ...

Increasing several array elements within a MongoDB object

I have been struggling with this problem for some time now. My goal is to update multiple array values in the same object with a single query. The data in the database appears as follows: id: 616f5aca5f60da8bb5870e36 title: "title" recommendations: ...

What is the best way to invoke a method within the $http body in AngularJS

When I try to call the editopenComponentModal method in another method, I encounter the following error: angular.js:13920 TypeError: Cannot read property 'editopenComponentModal' of undefined EditCurrentJob(job) { this.$http.put(pr ...

Is there a way to activate a function in one component from another within a Next.js application?

As mentioned in the title, I am working with 2 custom components within a basic NextJS application: <section> <CompA></CompA> <CompB></CompB> </section> I am trying to figure out how to have a button inside Comp ...

Could my reliance on useEffect be excessive? - Sorting through information based on the latest search criteria

My main goal was to implement a feature where users can filter data by clicking on checkboxes. The filtered data should persist even after a refresh. I have two components in place for this functionality: ShopPlants, responsible for displaying and filterin ...

Another option for handling a series of conditional statements instead of a bulky

Can someone help me with a coding issue I'm facing? I have an application that contains a large number of buttons which I need to trigger using keyboard presses. Currently, I am using a switch statement for this purpose. However, as the number of butt ...

Extract information from a URL using Regular Expressions

On my page, I have a list of blog post links: <ul class="postlist"> <li><a href="http://someblog.it/blogpost/7/-----.aspx">Post One</a></li> <li><a href="http://someblog.it/blogpost/32/----------.aspx">Post Two< ...