Guest User

Javascript dice game

a guest
Nov 21st, 2019
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. "use strict";
  2.  
  3. window.addEventListener('load',Initieer);
  4.  
  5. // Global variabels
  6. var image_tracker = 'white';
  7. var throws = [];
  8.  
  9. function Initieer(){
  10. var btn = document.querySelector('.btn-yellow');
  11. document.querySelector('.btn-yellow').addEventListener('click', createRandomDices);
  12. document.querySelector('.dice').addEventListener("click",holdDice,false);
  13. console.log("The holdDice function has been called");
  14. }
  15.  
  16. // Function to change the color of the dice whenever it is selected.
  17. // A tracker to keep track of the color it has, so you can hold(red) / roll(white) the dice.
  18. function holdDice(){
  19. console.log("used the function holdDice");
  20.  
  21. Array.from(document.querySelectorAll(".dice")).forEach(d=>{
  22. d.onclick = function(){
  23. console.log("clicked:", this);
  24. this.classList.toggle("locked");
  25. var srcImage = this.src;
  26. console.log("The image src of this dice is " + srcImage);
  27.  
  28. if(this.src.split("_red.png").length > 1){
  29. // assume it was red
  30. this.src = this.src.replace("_red.png",".png");
  31. } else {
  32. // assume it was white
  33. this.src = this.src.replace(".png","_red.png");
  34. }
  35. }
  36. })
  37. }
  38.  
  39. function createRandomDices(){
  40.  
  41. const diceElements = Array.from(document.querySelectorAll('.dice'));
  42.  
  43. // Generate random numbers
  44. const dice = [
  45. {randomNumber: Math.floor(Math.random() * 6) + 1},
  46. {randomNumber: Math.floor(Math.random() * 6) + 1},
  47. {randomNumber: Math.floor(Math.random() * 6) + 1},
  48. {randomNumber: Math.floor(Math.random() * 6) + 1},
  49. {randomNumber: Math.floor(Math.random() * 6) + 1}
  50. ];
  51.  
  52. for(let i in dice) {
  53. dice[i].image = 'img/dice' + dice[i].randomNumber + '.png';
  54. }
  55.  
  56. //Display the dices on the page
  57. document.getElementById('dice-1').src = 'img/dice' + dice[0].randomNumber + '.png';
  58. document.getElementById('dice-2').src = 'img/dice' + dice[1].randomNumber + '.png';
  59. document.getElementById('dice-3').src = 'img/dice' + dice[2].randomNumber + '.png';
  60. document.getElementById('dice-4').src = 'img/dice' + dice[3].randomNumber + '.png';
  61. document.getElementById('dice-5').src = 'img/dice' + dice[4].randomNumber + '.png';
  62. }
Advertisement
Add Comment
Please, Sign In to add comment