3

I am creating a simple game that has 9 divisions and each 8 of the divisions have a penguin hidden in them and the 9th one has a monster. Now my game works fine but what I want to do is every time I load the page, arrangement of the divisions should change so as to add randomness to the game.

Here is my code:

$(document).ready(function() {
  //This code will run after your page loads
  $('body').on('mousedown', '.yeti', function(event) {
    alert("Yaaaarrrr!");
  });
});
<div class="gameholder">
  <div class="title"></div>
  <div class="penguin1"></div>
  <div class="penguin2"></div>
  <div class="penguin3"></div>
  <div class="penguin4"></div>
  <div class="penguin5"></div>
  <div class="penguin6"></div>
  <div class="penguin7"></div>
  <div class="penguin8"></div>
  <div class="yeti"></div>
</div>

After adding images and some positioning to the div's this is how it looks

:

Pugazh
  • 9,453
  • 5
  • 33
  • 54
Ankur Chavda
  • 173
  • 4
  • 17
  • Remove the divs from the DOM and then add them back in random order. It would probably help if you arranged it so they weren't siblings of `.title` or else make it easier to select them without `.title` – Matt Burland May 31 '16 at 14:41
  • 1
    http://stackoverflow.com/questions/7070054/javascript-shuffle-html-list-element-order – Pimmol May 31 '16 at 14:44
  • The following might be of help: http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery – David Wilkinson May 31 '16 at 14:46

2 Answers2

5

Keeping Your Animals Contained

Consider creating a container for all of your game elements as you only want to randomize their order as you don't want to get the title mixed up in all of this :

<div class='game-container'>
    <div class="penguin1"></div>
    <div class="penguin2"></div>
    <div class="penguin3"></div>
    <div class="penguin4"></div>
    <div class="penguin5"></div>
    <div class="penguin6"></div>
    <div class="penguin7"></div>
    <div class="penguin8"></div>
    <div class="yeti">
</div>

Shuffling Them Around

This should make them easier to randomize through a simple jQuery extension function like this one mentioned in this related thread :

$.fn.randomize = function(selector){
    (selector ? this.find(selector) : this).parent().each(function(){
        $(this).children(selector).sort(function(){
            return Math.random() - 0.5;
        }).detach().appendTo(this);
    });
    return this;
};

You can combine these two approaches by then simply calling the following when your page has loaded :

$(document).ready(function(){
    // Define your randomize function here

    // Randomize all of the elements in your container
    $('.game-container').randomize('div');
});

Example

enter image description here

$.fn.randomize = function(selector){
    (selector ? this.find(selector) : this).parent().each(function(){
        $(this).children(selector).sort(function(){
            return Math.random() - 0.5;
        }).detach().appendTo(this);
    });

    return this;
};
// Randomize all of the <div> elements in your container
$(".game-container").randomize('div');
.game-container { width: 300px; }

.penguin { background: url('http://vignette1.wikia.nocookie.net/farmville/images/b/be/Baby_Penguin-icon.png/revision/latest?cb=20110103080900'); height: 100px; width: 100px; display: inline-block; }
.yeti { background: url('http://www.badeggsonline.com/beo2-forum/images/avatars/Yeti.png?dateline=1401638613'); height: 100px; width: 100px; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='game-container'>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='penguin'></div>
  <div class='yeti'></div>
  <div class='penguin'></div>
</div>
Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Excellent :) . However, I'm a little new to javascript and jquery. Could you please explain what the randomize function is doing? – Ankur Chavda May 31 '16 at 19:26
  • 1
    Sure. You can see an [annotated example of the function here](https://gist.github.com/Rionmonster/e8a4bfb3c83d87744e197753f144f2fe), which hopefully helps clear things up a bit. – Rion Williams May 31 '16 at 19:40
  • Can you please explain why do we need to write this.something? What does 'this' mean? And as you annotated " This will attempt to find a selector if one exists (this.find(selector)) or it will use the current object (this) ", what is the current object? – Ankur Chavda Jun 01 '16 at 10:44
0
<body>
    <div class="gameholder">
        <div class="title"></div>
        <div class="penguin1"></div>
        <div class="penguin2"></div>
        <div class="penguin3"></div>
        <div class="penguin4"></div>
        <div class="penguin5"></div>
        <div class="penguin6"></div>
        <div class="penguin7"></div>
        <div class="penguin8"></div>
        <div class="yeti"></div>
    </div>
    <script type="text/javascript">
    $(document).ready( function() {
    $('.gameholder div').shuffle();

   /*
   * Shuffle jQuery array of elements - see Fisher-Yates algorithm
   */
   jQuery.fn.shuffle = function () {
        var j;
        for (var i = 0; i < this.length; i++) {
            j = Math.floor(Math.random() * this.length);
            $(this[i]).before($(this[j]));
        }
        return this;
    };

    //This code will run after your page loads
    $('body').on('mousedown', '.yeti', function(event) {

        alert("Yaaaarrrr!");

    });
});
</script>

Here you would like to know what this 2 line of code is doing ->

j = Math.floor(Math.random() * this.length); // (1)
$(this[i]).before($(this[j])); // (2)
  1. Here in line 1 first I am getting random number using Math.random, Math.random gives you floating number ranging from zero to one. so here I am multiplying that number with length, so it gives me random floating number from zero to length, now I am flooring this number to integer, to get integer from zero to length - 1

  2. If we have a selector $('#b').before('#a') then it puts #a element before #b element, so here we are getting one by one element and putting them in the random order.

Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52