简体   繁体   English

取两个mathrandom值并将它们添加到循环中

[英]Taking two mathrandom values and adding them on loop

I have to make a game of dice where I add the values of both the dice and give the sum. 我必须做一个骰子游戏,我在其中添加两个骰子的值并给出总和。 You get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous sum (like 4 mentioned earlier). 如果两个骰子都以相同的数字结束(例如2和2,即4),则再次转动骰子,然后再将2个新数字添加到前一个总和(如前面提到的4个)。 For example - 1st try 3 and 3, sum is 6. 2nd try 4 and 5, sum is 6 + 4 + 5 = 15 例如 - 第一次尝试3和3,总和是6.第二次尝试4和5,总和是6 + 4 + 5 = 15

I'm able to get the first sum right, but the subsequent numbers are getting messed up sometimes even giving twice as much. 我能够得到第一笔总和,但随后的数字有时会变得混乱甚至两倍。

function oneRandom(){
    var my1 = Math.floor(Math.random() * 6 ) +1 ;   
    var my2 = Math.floor(Math.random() * 6 ) +1 ;
     var num1 = Number(my1);
    var num2 = Number(my2);

    var sum = num1 + num2;
    console.log(sum);
    var resultfield = document.getElementById("total").innerHTML = "<h1>"+sum+"</h1>";

    document.getElementById("cilc").style.display = "none";
    if (getImage.src == get2.src){
        document.getElementById("cilc").style.display = "block";
        var sum2 = num1 + num2;
        var total = sum2 + sum;
    var resultfield = document.getElementById("total").innerHTML = "<h1>"+total+"</h1>";
    }

}

The getImage and get2 are arrays to match dice images to give another turn in case of same numbers loading. getImage和get2是匹配骰子图像的数组,以便在加载相同数字的情况下进行另一次转弯。

You can try this, 你可以试试这个,

 function rollDice (times) { var num1 = Math.floor(Math.random() * Math.floor(6)); var num2 = Math.floor(Math.random() * Math.floor(6)); console.log(times, num1, num2); var total = num1 + num2; return num1 === num2 ? total + rollDice(times + 1) : total; } console.log(`result is ${rollDice(0)}`); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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