index.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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('img');
  40. dice_value = rand_dice();
  41. dice_tag.alt = dice_value;
  42. dice_tag.src = 'img/dice/' + dice_value + '.svg';
  43. roll_tag.appendChild(dice_tag);
  44. }
  45. prependChild(document.getElementById('rolls'), roll_tag);
  46. }
  47. </script>
  48. <style>
  49. footer {
  50. color: gray;
  51. font-size: 0.64em;
  52. margin-top: 1em;
  53. }
  54. footer a {
  55. color: gray;
  56. text-decoration: none;
  57. }
  58. footer a:hover {
  59. text-decoration: underline;
  60. }
  61. #rolls div {
  62. margin-top: 0.4em;
  63. }
  64. #rolls img {
  65. height: 3em;
  66. margin-right: 0.4em;
  67. }
  68. </style>
  69. <p>
  70. dices
  71. <input id="dice_num" type="number" min="1" max="32" value="6">
  72. <input type="button" onclick="decrement()" value="-">
  73. <input type="button" onclick="increment()" value="+">
  74. <input type="button" onclick="roll()" value="roll">
  75. </p>
  76. <div id="rolls"></div>
  77. <footer>
  78. <a href='https://git.hammerle.me/fphammerle/dice'>src</a>
  79. | icons from
  80. <a href="https://www.flaticon.com/authors/freepik" title="Freepik">flaticon:freepik</a>
  81. </footer>
  82. </html>