Tommi Tiihonen Tommi Tiihonen - 27 days ago 8
HTML Question

Rolling 2 dice randomly (with URLs)

I have this problem with rolling 2 dice, and then, if they match, the script should return which pair it was.

I have the dice pics on my server.

I must be doing some very simple things wrong but can't now figure out what the are.

Here is the URL of to this tasks page that I've made: http://rockworksstudio.fi/mamk/js/ot4/ot4b.html

And here is my current code on that page:



var n1 = document.getElementsById("noppa1");
var n2 = document.getElementsById("noppa2");
var pari = document.getElementById("pari");
var pairs = ["Ykköset", "Kakkoset", "Kolmoset", "Neloset", "Vitoset", "Kutoset"];

function pelaa() {
var dice1 = Math.floor(Math.random() * (6)) + 1;
var dice2 = Math.floor(Math.random() * (6)) + 1;
var url1 = "noppakuvat/noppa" + dice1 + ".jpg";
var url2 = "noppakuvat/noppa" + dice2 + ".jpg";

n1.src = url1;
n2.src = url2;

if dice1 == dice2 {
pari.innerHTML = pairs.[dice1 - 1];
} else pari.innerHTML = "";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button type="button" id="button" onClick="pelaa()">Pelaa</button>
<p>
<img src="noppakuvat/noppa1.jpg" id="noppa1" />
<img src="noppakuvat/noppa1.jpg" id="noppa2" />
</p>

<p id="pari"></p>




Answer
  • if dice1 == dice2 { needs to be if (dice1 == dice2) {
  • pari.innerHTML = pairs.[dice1 - 1]; should be without the dot.
  • document.getElementsById needs to be singular

Thanks Andrew Bone for the dice :)

var n1 = document.getElementById("noppa1");
var n2 = document.getElementById("noppa2");
var pari = document.getElementById("pari");
var pairs = ["Ykköset", "Kakkoset", "Kolmoset", "Neloset", "Vitoset", "Kutoset"];

function pelaa() {
  var dice1 = Math.floor(Math.random() * (6)) + 1;
  var dice2 = Math.floor(Math.random() * (6)) + 1;
  var url1 = "https://www.random.org/dice/dice" + dice1 + ".png";
  var url2 = "https://www.random.org/dice/dice" + dice2 + ".png";

  n1.src = url1;
  n2.src = url2;

  if (dice1 == dice2) {
    pari.innerHTML = pairs[dice1 - 1];
  } else {
    pari.innerHTML = "";
  }
}
https://www.random.org/dice/dice1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" id="button" onClick="pelaa()">Pelaa</button>
<p>
  <img src="https://www.random.org/dice/dice1.png" id="noppa1" />
  <img src="https://www.random.org/dice/dice1.png" id="noppa2" />
</p>

<p id="pari"></p>