Game Development Reference
In-Depth Information
addBlock
might seem like a complex function at first, but it is really very simple. The code looks
difficult because of all the constants we use to calculate the position of a Block. Let's get rid of the
easy part first: finding the color of the block. We get a random color from the array
CurrentLevel.allowedColors that we set in the DifficultyLevel class. First, we find an index into the
allowedColors array like so:
var randomColor= Math.floor(Math.random()*currentLevel.allowedColors.length);
Then, we use that index to store that color for later use:
var blockColor = currentLevel.allowedColors[randomColor];
Now, we need to create an instance of
Block
and put it into
tempBlock
. Here is a rundown of the
parameters we will pass to the Block constructor:
blockColor
: The color we just found from the
currentLevel.allowedColors
array
tileSheet
: A reference to the tile sheet we created that holds the graphics for the blocks
row
: The row index in the board array passed to us from
replaceBlocks
col
: The
col
index in the board array passed to us from
replaceBlocks
(row*BLOCK_HEIGHT)+Y_PAD+(row*ROW_SPACING)
: The
fallEndY
property for
Block
row*BLOCK_HEIGHT
is the
y
value of the row position for this
Block
.
Y_PAD
is the distance from the
top of the screen to the start of the
Block
s in the grid.
row*ROW_SPACING
represents all the spaces
between each row of
Block
s. Add all of those values together to get the final position of the
Block
on the screen.
public function addBlock(row:Number, col:Number):Block {
var randomColor:Number =
Math.floor(Math.random()*currentLevel.allowedColors.length);
var blockColor:Number = currentLevel.allowedColors[randomColor];
tempBlock = new Block(blockColor, tileSheet, row, col,
(row*BLOCK_HEIGHT)+Y_PAD+(row*ROW_SPACING),(Math.random()*10)+10 );
Next, we will set the starting
x
value for the
Block
, which is very similar to the
fallEndY
value,
except we use
BLOCK_WIDTH
,
X_PAD
, and
COL_SPACING
as our values to plug into the calculation. The
starting
y
value is simply
0-BLOCK_HEIGHT
so the
Block
will start just off the screen. Figure 8-3 shows
how the constant values are used to calculate where blocks start and end in Color Drop.