骰子滚动游戏的重置功能

时间:2015-07-04 19:43:50

标签: javascript html arrays reset dice

我已经在这段代码上工作了一段时间用于学习目的。我终于让程序工作了,但是当你掷骰子时,它只允许骰子滚动一次;如果你想第二次掷骰子,你必须刷新屏幕。

我正在尝试为这个程序构建一个重置功能,这样我可以在没有屏幕刷新的情况下多次掷骰子。

我已经建立了重置功能,但是它没有工作......它清除了DIV,但不允许程序再次执行。

有人可以帮帮我吗?

*我是Javascript的半经纪人,我正在制作这样的程序来练习我的技能。

HTML:

$mysqli = mysqli_connect('HOST', 'USEER', 'PASS', 'DB');

JavaScript的:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Dice Rolling</title>
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>
  <header>
    <h1>Roll the Dice!</h1>
    <h2>By: Jeff Ward</h2>
  </header>
  <h3>Setup your Dice!</h3>
  <div id="left">
    <form id="numberOfDiceSelection">
      Number Of Dice Used:
      <br>
      <input id="numberOfDice" type="text" name="numberOfDice">
    </form>
  </div>
  <div id="right">
    <form id="diceSidesSelection">
      Number of sides on each dice:
      <br>
      <input id="diceSides" type="text" name="diceSides">
    </form>
  </div>
  <button type="button" onclick="roll()">Roll the Dice!</button>
  <button type="button" onclick="reset()">Reset Roll</button>


  <div id="output">

  </div>
  <div id="output1">

  </div>
  <script src="js/script.js"></script>

</body>

</html>

谢谢!

JSFiddle Link = https://jsfiddle.net/kkc6tpxs/

1 个答案:

答案 0 :(得分:1)

我重写并做了你想做的事情:

https://jsfiddle.net/n8oesvoo/

var log = logger('output'),
    rollBtn = getById('roll'),
    resetBtn = getById('reset'),
    nDices = getById('numofdices'),
    nSides = getById('numofsides'),
    dices = null,
    sides = null,
    rolls = [],
    doubles=0;

rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);


function rollHandler() {
    resetView();
    sides = nSides.value;
    dices = nDices.value;
    doubles=0;
    rolls=[];

    if(validateInput()) {
        log('invalid input');
        return;
    }
    //rolling simulation
    var rolled;
    while (dices--) {
        rolled = Math.ceil(Math.random()*sides);
        log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled  +'!');
        rolls.push(rolled);
    }

    //finding doubles
    //first sort: you can use any way to sort doesnt matter
    rolls.sort(function(a,b){
      return (a>b?1:(a<b)?0:-1);
    });

    for (var i =0; i < rolls.length; i++) {
        if (rolls[i] == rolls[i+1]) {
            doubles++;
            i++;
        }
    }
    if (doubles>0) log("You rolled " + doubles + " doubles");

}

function resetHandler(){
    resetView();
    nDices.value = nSides.value = '';
}


function resetView() {
    getById('output').innerText = '';
}


function validateInput(){
    return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}


function logger(x) { var output = getById(x); 
    return function(text){
        output.innerText += text + '\n';
};}

function getById(x){ return document.getElementById(x); }