简体   繁体   中英

How do I properly use a “for loop” to roll one die (or multiple) within a function of another die roll?

I'm a student and new to computer programing and had a quick question regarding a project I'm working on and how I am suppose to make it work.

This is what the requirement is: Instead of having two dice initially showing on the page, start with only one die image, and build the second image tag inside a for loop in your function. Remove the first block of code (that rolls the first die) and instead put the code for the second die (the one that builds the img tag) into a "for" loop that runs twice.

<script type="text/javascript">
        //double dice script
        function SelectImage2() {
            roll2 = Math.floor(Math.random() * 6) + 1;
            imgName2 = '../images/die' + roll2 + '.gif';
            document.getElementById('dieImg2').src = imgName2;

            roll3 = Math.floor(Math.random() * 6) + 1;
            imgName3 = '../images/die' + roll3 + '.gif';
            document.getElementById('dieImg3').src = imgName3;


        }

    </script>

<div style="text-align:center">
        <p>
            <img id="dieImg2" alt="die image"
            src="../images/die2.gif" >

            <img id="dieImg3" alt="die image"
            src="../images/die3.gif" >
        </p>
        <input type="button" value="Roll until doubles" onclick="SelectImage2();">

    </div>

Basically, I guess I'm just looking for someone to maybe explain the for loop function and how I am suppose to call one roll within another roll? Any advice would be greatly appreciated! Thanks!

Use something like

function SelectImage2() {
    for (var i = 2; i <= 3; ++i) {
        var roll = Math.floor(Math.random() * 6) + 1,
            imgName = '../images/die' + roll + '.gif';
        document.getElementById('dieImg' + i).src = imgName;
    }
}

Or, if you want compact code,

function SelectImage2() {
    for (var i = 2; i <= 3; ++i) {
        document.getElementById('dieImg' + i).src
           = '../images/die' + ( 1 + Math.random() * 6 | 0 ) + '.gif';
    }
}

Notes

  • Always declae your variables using var !
  • number|0 is a simple and fast way to round towards 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM