Skip to content
Advertisement

PHP/JavaScript random number

I am playing around with JavaScript and trying to choose some random images.

What I’m actually trying to do:

I have $totalsixes = rand(1,6); in PHP, and let’s say that chose 4. Then in JavaScript I want to show 4 images with the number 6 and 2 others with random numbers from 1-5.

Here’s what I’ve tried so far:

<?php
$totalsixes = rand(1,6);
?>
<script type="text/javascript">
function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] =     o[j], o[j] = x);
    return o;
};

var imagePaths = shuffle([
    "http://website.com/spill2/terninger/1.gif",
    "http://website.com/spill2/terninger/2.gif",
    "http://website.com/spill2/terninger/3.gif",
    "http://website.com/spill2/terninger/4.gif",
    "http://website.com/spill2/terninger/5.gif",
    "http://website.com/spill2/terninger/6.gif"]);

for(var i = 0; i < imagePaths.length; i++) {
    document.getElementById("randterning" + i).src = imagePaths[i];
}
</script>

as you may see above the $totalsixes have no meaning at all in the code yet, as I don’t know how to tell the JavaScript to show X of sixes ($totalsixes chose the X), and also I don’t know how to make the JavaScript chose a random number for those others dices. Total there is always 6 dices.

A screen shot of an example what I want to make:

http://prntscr.com/9iqiag

Advertisement

Answer

<?php $totalsixes = rand(1,6); ?>

<script type="text/javascript">
    function shuffle(o){
        for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] =  o[j], o[j] = x);
        return o;
    }

    var imagePaths = [
        "http://website.com/spill2/terninger/1.gif",
        "http://website.com/spill2/terninger/2.gif",
        "http://website.com/spill2/terninger/3.gif",
        "http://website.com/spill2/terninger/4.gif",
        "http://website.com/spill2/terninger/5.gif",
        "http://website.com/spill2/terninger/6.gif"];

    var images = []; // <- edit here
    for(var x= 0 ; x<6; x++){
         images[x] = x < <?echo $totalsixes?> ?  imagePaths[5] : imagePaths[Math.floor(Math.random() * 5)];
              //^ edit here
    }
    images = shuffle(images);

    for(var i = 0; i < imagePaths.length; i++) {
        document.getElementById("randterning" + i).src = images[i];
    }
</script>

if I understood correctly, the result is a table with ‘rand’ sixes and all the other are random dice but six

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement