简体   繁体   中英

Having issues with Javascript dice game

I'm trying to get one button to fire two functions. It's a basic dice based game: the player die on top works fine, but the computer die doesn't give a value.

 function Welcome() { alert("Welcome " + document.getElementById("fname").value + "!"); } function oldEnough(age) { if (age< 18) {alert("UNDER 18 LEAVE NOW"); } } //player dice roll// function rollDice() { var die1 = document.getElementById("die1"); var die2 = document.getElementById("die2"); var status = document.getElementById("status"); //random number between 1 and 6(whole number)// var d1 = Math.floor(Math.random() * 6) + 1; var d2 = Math.floor(Math.random() * 6) + 1; var diceTotal = d1 + d2; //shows the random number value// die1.innerHTML = d1; die2.innerHTML = d2; status.innerHTML = "You Rolled "+diceTotal+"."; if (d1 == d2){ status.innerHTML +=" Doubles! Roll Again "; } } //computer dice roll// function compDice() { var die3 = document.getElementById("die3") var die4 = document.getElementById("die4") var status2 = document.getElementById("status2") var d3 = Math.floor(Math.random() *6) +1; var d4 = Math.floor(Math.random() * 6) +1; var diceTotal = d3 + d4; die3.innerHTML = d3; die4.innerHTML = d4; status2.innerHTML = "Computer Rolled "+diceTotal+"."; } 
 div.dice{ float:left; width:32px: background:#D6D6D6; border:#999 1px solid; padding:10px; font-size:24px; text-align:center; margin:5px; } div.die{ float:left; width:32px: background:#D6D6D6; border:#999 1px solid; padding:10px; font-size:24px; text-align:center; margin:5px; } 
 <form action="#" method="get"> <p> Player Name: <input id="fname" name="fname" type="text" size="20" maxlength="20" onblur="Welcome()" /> </p> Age: <input id="age" name="age" id="age" type="text" size="3" maxlength="3" onBlur="oldEnough(this.value)"/> </p> <div id="die1" class="dice">0</div> <div id="die2" class="dice">0</div> <button onclick="rollDice()";"compDice()">Roll Dice</button> <h2 id="status" style="clear:left;"></h2> <div id="die3" class="die">0</div> <div id="die4" class="die">0</div> <h2 id="status2" style="clear:right;"></h2> 

Change this:

<button onclick="rollDice()";"compDice()">Roll Dice</button>

to:

<button onclick="rollDice();compDice()">Roll Dice</button>

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