Tallying the number of iterations a loop undergoes

I have been tasked with developing a dice game where the player places a bet amount and rolls the dice until they run out of money. My goal is to track the number of times the dice has been rolled before the player goes broke, and store this data in an array. I am using a do..while loop to handle the dice rolling process but I'm unsure how to keep count of the iterations and save it in an array. Any guidance on how to achieve this would be greatly appreciated!

   <script>
        var rolls = new Array();
        var maxMoney = new Array();
        var rollCountMoney = new Array();
        function rollDice(){
        do {
        var userInput = parseInt(document.getElementById("bet").value); 
        var wallet = userInput; 
        var d1 = Math.floor(Math.random() * 6) + 1;
        var d2 = Math.floor(Math.random() * 6) + 1;
        var diceTotal = d1 + d2;
            if(diceTotal === 7) {
                document.getElementById("bet").value = wallet += 4;
                alert("your rolled a " +diceTotal +"! You win $4");
        } else {
                document.getElementById("bet").value = wallet -= 1;
                alert("your rolled a " +diceTotal +"! You lose $1");
            }
        } while (wallet > 0) { 
        }

        } 
    </script>
</head>
<body>          
    <div class="container-fluid">
        <div class="page-head"> 
            <h1 align="center">Lucky Sevens</h1>
        </div>
    </div>  
    <div class="container" align="center"> 
        <table style="border: 1px solid black"> 
            <tr>
                <th><h3 align="center">Lucky Sevens</h3></th>
            </tr>
            <tr>
                <td>
                    <form>
                        Starting Bet: 
                        <input id="bet" type="text"/>
                    </form>
                </td>   
            </tr>
            <tr>
                <td align="center">
                    <button onclick="rollDice()">Play</button>
                </td>
            </tr>
        </table>
    </div> 

Answer №1

Based on your code and variable naming conventions, you can store the result in the following way...

var rolls = new Array();
var maxMoney = 0;//Maximum Amount of Money
var rollCountMoney = new Array();
var count = 0;

function rollDice() {
  do {
    count++;
    var inputAmount = parseInt(document.getElementById("bet").value);
    var wallet = inputAmount;
    var die1 = Math.floor(Math.random() * 6) + 1;
    var die2 = Math.floor(Math.random() * 6) + 1;
    var totalDiceValue = die1 + die2;
    rolls.push(totalDiceValue);//keep track of the dice total
    rollCountMoney.push(wallet);//keep track of the wallet amount
    if(wallet > maxMoney){
      maxMoney = wallet;//set max money
    }
    if (totalDiceValue === 7) {
      document.getElementById("bet").value = wallet += 4;
      alert("Round:" + count + ",you rolled a " + totalDiceValue + "! You win $4");
    } else {
      document.getElementById("bet").value = wallet -= 1;
      alert("Round:" + count + ",you rolled a " + totalDiceValue + "! You lose $1");
    }
  } while (wallet > 0) {}
  var displayMessage = "You have rolled the dice " + count + " times!";
  displayMessage += "<br>Rolls:" + rolls;
  displayMessage += "<br>maxMoney:" + maxMoney;
  document.getElementById("display").innerHTML = displayMessage;


}
<div class="container-fluid">
  <div class="page-head">
    <h1 align="center">Lucky Sevens</h1>
  </div>
</div>
<div class="container" align="center">
  <table style="border: 1px solid black">
    <tr>
      <th>
        <h3 align="center">Lucky Sevens</h3>
      </th>
    </tr>
    <tr>
      <td>
        <form>
          Starting Bet:
          <input id="bet" type="text" />
        </form>
      </td>
    </tr>
    <tr>
      <td align="center">
        <button onclick="rollDice()">Play</button>
      </td>
    </tr>
    <tr>
      <td align="center" id="display"></td>
    </tr>
  </table>
</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

Tap the <li> element in a select2 dropdown from Bootstrap using internjs

I am currently encountering an issue while trying to select values from a Bootstrap-select2 drop-down in my form during the process of writing some function tests. If Select2 is unfamiliar to you, here are some examples that may help: The drop-downs are ...

The issue of button onclick textfield validation malfunctioning

Within this container, there is a text field identified as 'codeCityId' along with a button that triggers an onclick method. When the button is clicked, the function will verify the input. function click()={ var valid = $('#codeCityId' ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

What is the best way to ensure that certain digits in this 2-dimensional array have zeros on their right side?

For this particular code, I created two separate 1D arrays to store multiplicands and multipliers. Then, I stored the multiplication results in a 2D array in order to add them together. { int n, m, i, j; printf("Enter the size of multiplicand (n): ...

How can one locate the text coordinates within a div using JavaScript?

My current task involves locating the exact coordinates of the word "The" within this Wikipedia page once it has been displayed, similar to the coordinates provided by Chrome's developer tools. See a screenshot of developer options here. <div>Th ...

How can you extract a specific property from a "stdClass" object by utilizing a foreach loop?

In my current project, I am working with an array that contains stdClass objects. My goal is to unserialize a specific property within each object in the array. However, I seem to be having trouble as the object remains serialized even after attempting t ...

Utilizing Browser and Operating System Information as Body Class

In order to achieve pixel-perfect styling, I want to include the OS and browser information in the body class. This is necessary because fonts may appear differently depending on the OS/browser configuration. After some research and experimentation, I came ...

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

The Gatsby node encounters an error while trying to create a new page

I am currently working on creating sub-pages for a projects category in Gatsby. The parent page for each project is generating correctly, but the sub-pages are not behaving as expected. Each project has the potential to have zero or multiple sub-pages, an ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Implementing personalized validation post-control initialization in an Angular 4 reactive form

I have been working on an Angular 4 application and using reactive forms. For one of my forms, I am trying to implement custom validation on a control after it has been initialized, based on whether a checkbox is checked or unchecked. CODE form.componen ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Is there a way to store a complete array within a single cell?

I am searching for a solution to assign an entire array to a cell in Google Apps Script and Google Sheets. My attempt at using cell.setValue(array) only resulted in the cell containing the first item of the array. var cell = SpreadsheetApp.getActiveSprea ...

Exploring the array of pointers by iterating through them in K&R

In K&R's book on page 109, the writelines function is shown written with an iteration of a pointer to an array of pointers: void writelines(char *lineptr[], int nlines) { while(nlines-- > 0) printf("%s\n", *lineptr++); } Quer ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...

Tips for properly formatting large numbers

I am facing a challenge with handling large numbers in my JavaScript code. I came across the nFormatter function for formatting large numbers but I am unsure how to integrate it into my existing code. Below is the nFormatter function that I found: functi ...

Tips on Moving a Bootstrap Modal Popup with the Arrow Keys on Your Keyboard

This example showcases the integration of Bootstrap's Default Modal Popup with jQuery UI Draggable Function. The JS fiddle link provided below contains the code snippet. $(document).ready(function() { $("#btnTest").click(function() { $(&a ...