我被分配了创建骰子游戏的任务。游戏的目标是下注$金额,骰子将反复滚动,直到用户用完钱。我必须计算用户在钱用完之前掷骰子的次数并将其存储在数组中。我使用了do..while循环来执行骰子滚动功能,我很困惑如何计算do..while循环运行的次数并将其存储在数组中。在正确的方向轻推将不胜感激!
<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>
答案 0 :(得分:0)
根据您的代码和变量名称。你可以保持这样的结果......
var rolls = new Array();
var maxMoney = 0;//Max Money
var rollCountMoney = new Array();
var count = 0;
function rollDice() {
do {
count++;
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;
rolls.push(diceTotal);//keep the roll
rollCountMoney.push(wallet);//keep the wallet
if(wallet > maxMoney){
maxMoney = wallet;//keep the max money
}
if (diceTotal === 7) {
document.getElementById("bet").value = wallet += 4;
alert("Round:" + count + ",your rolled a " + diceTotal + "! You win $4");
} else {
document.getElementById("bet").value = wallet -= 1;
alert("Round:" + count + ",your rolled a " + diceTotal + "! You lose $1");
}
} while (wallet > 0) {}
var displayMsg = "You have rolled " + count + " times!";
displayMsg += "<br>Rolls:" + rolls;
displayMsg += "<br>maxMoney:" + maxMoney;
document.getElementById("display").innerHTML = displayMsg;
}
<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>