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

:

3
  • 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 Commented May 31, 2016 at 14:41
  • 1
    stackoverflow.com/questions/7070054/… Commented May 31, 2016 at 14:44
  • The following might be of help: stackoverflow.com/questions/1533910/… Commented May 31, 2016 at 14:46

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent :) . However, I'm a little new to javascript and jquery. Could you please explain what the randomize function is doing?
Sure. You can see an annotated example of the function here, which hopefully helps clear things up a bit.
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?
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.

2 Comments

how does this.length evaluate? I am a little new to jquery and ' $(this[i]).before($(this[j])); ' too
@ankurchavda: I have updated the answer, see bottom part of my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.