index.html 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="utf-8" />
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  5. <title>Dice</title>
  6. <script>
  7. const DICE_NUM_MIN = 1;
  8. const DICE_RAND_MIN = 1;
  9. const DICE_RAND_MAX = 6;
  10. function rand_int(min, max) {
  11. return Math.floor(Math.random() * (max - min + 1)) + min;
  12. }
  13. function rand_dice() {
  14. return rand_int(DICE_RAND_MIN, DICE_RAND_MAX);
  15. }
  16. function get_dice_num() {
  17. n = parseInt(document.getElementById('dice_num').value);
  18. if(isNaN(n) || n < DICE_NUM_MIN) {
  19. return 1;
  20. }
  21. return n;
  22. }
  23. function set_dice_num(n) {
  24. document.getElementById('dice_num').value = Math.max(n, DICE_NUM_MIN);
  25. }
  26. function increment() {
  27. set_dice_num(get_dice_num() + 1);
  28. }
  29. function decrement() {
  30. set_dice_num(get_dice_num() - 1);
  31. }
  32. function prependChild(parent_tag, child_tag) {
  33. parent_tag.insertBefore(child_tag, parent_tag.firstChild);
  34. }
  35. function roll() {
  36. roll_tag = document.createElement('div');
  37. dice_num = get_dice_num();
  38. for(i=0; i<dice_num; i++) {
  39. dice_tag = document.createElement('span');
  40. dice_tag.appendChild(document.createTextNode(rand_dice() + ' '));
  41. roll_tag.appendChild(dice_tag);
  42. }
  43. prependChild(document.getElementById('rolls'), roll_tag);
  44. }
  45. </script>
  46. <p>
  47. dices
  48. <input type="text" id="dice_num" align="middle"
  49. type="number" min="1" size="2" value="6">
  50. <input type="button" onclick="decrement()" value="-">
  51. <input type="button" onclick="increment()" value="+">
  52. <input type="button" onclick="roll()" value="roll">
  53. </p>
  54. <div id="rolls"></div>
  55. </html>