Chapter 7, Exercise 1 – Ending Levels Efficiently

Toward the end of each level, the player can only have bubbles of one, two, or three colors left on the board. Giving them a bubble of a color that won’t match any of these causes the player to waste a shot and can make the game more difficult to complete. Change the bubble‑generating algorithm so that it gives players only bubbles of a color that can potentially form a match. For example, if only red and blue bubbles remain, the firing bubble should be either red or blue. You will need to amend getNextBubble in game.js and choose a bubble type from one of the types that exist in the Board object.

There are two stages to this:

  1. Work out which types of bubbles still existing on the board
  2. Only choose from those types of bubbles

This process will work whether the board is full of bubbles or only has a handful remaining.
First, we’re going to add a new method to Board.js to return an array containing the types of bubbles that exist on the board. This doesn’t need to be sorted and we just want the four type values:

var Board = function(){
  …
  this.isEmpty = function(){
    return this.getBubbles().length == 0;
  };
  this.getTypes = function(){
    var types = [];
    var bubbles = this.getBubbles();
    for(var i=0;i<bubbles.length;i++){
      var bubble = bubbles[i];
      if($.inArray(bubble.getType(), types) == -1){
        types.push(bubble.getType());
      }
    }
    return types;
  };
  return this;
};

This uses one of jQuery’s utility functions to check whether an element already exists in an array:

$.inArray(bubble.getType(), types)

You can read about how this works here: http://api.jquery.com/jquery.inarray/.

The return result will be an array that might look like this: [3,0,2,1] at the start of the game, which represents that all four bubble types are present. Towards the end, it might only by [0,3], which would mean only two bubble types are left.

Next, we want to choose from these available bubble types when we create a new bubble. We can do this in the getNextBubble function in game.js:

var getNextBubble = function(board){
var types = board.getTypes();
  var type = types[Math.floor(Math.random() * types.length)];
  var bubble = BubbleShoot.Bubble.create(null,null,type);
  bubbles.push(bubble);
  bubble.setState(BubbleShoot.BubbleState.CURRENT);
  bubble.getSprite().addClass("cur_bubble");
  var top = 470;
  var left = ($("#board").width() - BubbleShoot.ui.BUBBLE_DIMS)/2;
  bubble.getSprite().css({
    top : top,
    left : left
  });
  $("#board").append(bubble.getSprite());
  BubbleShoot.ui.drawBubblesRemaining(numBubbles);
  numBubbles--;
  return bubble;
};

Now, if you get towards the end of a level, you should never see a bubble of a color that isn’t already present on the board.

Leave a Reply

Your email address will not be published. Required fields are marked *