We’ve almost got a complete working game, and in this chapter we’ll look at adding the game logic to make the tetriminos fall on their own and keep score. To make the tetriminos fall, we need to lower the position of the current piece by one block at regular intervals. To do this, we need to create a timer object that will call a function every so often. We’ll create another global variable at the start of our code called timer.
var timer; //Game timer
We can start and clear the timer by using the setInterval and clearInterval functions, which are built into JavaScript. The setInterval function takes two parameters and returns a timer object that we assign to our global variable. The first argument is the function that we want to call, and the second argument is the time interval between function calls in milliseconds. It’s a good idea to use the clearInterval function on our timer object before creating a new timer to make sure that any previous timers assigned to this variable are removed. Additionally, since we are now going to let the computer control when to add new blocks, we’ll draw the first tetrimino in the initialize function. The following lines should be added to the end of the initialize function.
//Draw the current tetrimino
drawTetrimino(x,y,t,o,1);
//Redraw the grid
drawGrid();
//Start the game timer
clearInterval(timer);
timer = setInterval(function(){gameStep()}, 1000);
The function we’ve decided to call is the gameStep function, which I’ve defined below.
/*************************************************
Updates the game state at regular intervals
*************************************************/
function gameStep() {
//Erase the current tetrimino
drawTetrimino(x,y,t,o,0);
//Check if the tetrimino can be dropped 1 block
y2 = y - 1;
if(drawTetrimino(x,y2,t,o,-1))
y = y2;
else {
//Redraw last tetrimino
drawTetrimino(x,y,t,o,1);
//Check if any lines are complete
checkLines();
//Create a new tetrimino
t2 = 1 + Math.floor((Math.random()*7));
x2 = 4;
y2 = 18;
o2 = 0;
//Check if valid
if(drawTetrimino(x2,y2,t2,o2,-1)) {
t = t2;
x = x2;
y = y2;
o = o2;
}
else {
alert("Game Over");
initialize();
return;
}
}
//Draw the current tetrimino
drawTetrimino(x,y,t,o,1);
//Redraw the grid
drawGrid();
}
As of now, this function will be called every 1000 milliseconds, or once every second. The logic in this function is pretty straightforward. We follow the same steps as when we check for a down arrow key-press, but we take additional action if a collision occurs. If the block cannot drop any farther, we need to redraw it (since we erased it to do the collision checks) and then create a new tetrimino at the top of the screen. If this new tetrimino can’t be drawn, because we’ve stacked the blocks too high, then we need to alert the player that the game is over and then restart the game by calling the initialize function and returning. If the game continues, we update the display by drawing the current tetrimino and then redrawing the grid.
The line I haven’t explained yet is the call to the function checkLines() after redrawing the tetrimino that can’t be dropped anymore. This is another function that we need to write that will remove completed lines from the grid. The complete function looks like this:
/*************************************************
Removes completed lines from the grid
*************************************************/
function checkLines() {
//Loop over each line in the grid
for(i = 0; i < 20; i++) {
//Check if the line is full
full = true;
for(j = 0; j < 10; j++)
full = full && (grid[i][j] > 0);
if(full) {
//Loop over the remaining lines
for(ii = i; ii < 19; ii++) {
//Copy each line from the line above
for(j = 0; j < 10; j++)
grid[ii][j] = grid[ii+1][j];
}
//Make sure the top line is clear
for(j = 0; j < 10; j++)
grid[19][j] = 0;
//Repeat the check for this line
i--;
}
}
}
This is perhaps the most complicated function we’ve created so far, but it shouldn’t be too hard to figure out what’s going on. The outer loop uses the variable i to check each line of the grid. Then for each line, we check to see if all of the grid cells contain nonzero blocks, similar to how we checked for collisions by using the logical AND operator. If we discover that the line is full, it needs to be removed and all of the lines above it should fall down by one line. We do this by creating another loop variable ii that goes through the remaining lines (except the very top one) and copies each grid cell from the line above. We can’t do this for the top line since there is nothing to copy from, so we manually set everything in this line to zero. Finally, we need to decrement the outer loop variable i so that we check this line again. Since we just lowered everything by one line, the current line is new and needs to be checked again.
The last thing we need to do is modify the keyDown function. We can remove the else block that we were using to add new tetriminos since that is now handled automatically. The other change is that we need to add a call to the gameStep() function at the end of the space-bar condition block. This performs all of the line checks we just implemented and immediately creates a new tetrimino at the top of the screen rather than having to wait for the gameStep() function to be called automatically. The complete code should now look like this:
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<script>
//Golbal variables
var ctx; //Canvas object
var t; //Tetrimino type
var x, y; //Tetrimino position
var o; //Tetrimino orientation
var grid; //Game state grid
var timer; //Game timer
/************************************************
Initialize the drawing canvas
************************************************/
function initialize() {
//Get the canvas context object from the body
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
//Initialize tetrimino variables
t = 1 + Math.floor((Math.random()*7));
x = 4;
y = 18;
o = 0;
//Create an empty game state grid
grid = new Array(20);
for(i = 0; i < 20; i++) {
grid[i] = new Array(10);
for(j = 0; j < 10; j++)
grid[i][j] = 0;
}
//Draw the current tetrimino
drawTetrimino(x,y,t,o,1);
//Redraw the grid
drawGrid();
//Start the game timer
clearInterval(timer);
timer = setInterval(function(){gameStep()}, 1000);
}
/************************************************
Draws the current game state grid
************************************************/
function drawGrid() {
//Clear the canvas
ctx.clearRect(0,0,200,400);
//Loop over each grid cell
for(i = 0; i < 20; i++) {
for(j = 0; j < 10; j++)
drawBlock(j, i, grid[i][j]);
}
}
/************************************************
Draws a block at the specified game coordinate
x = [0,9] x-coordinate
y = [0,19] y-coordinate
t = [0,7] block type
************************************************/
function drawBlock(x, y, t) {
//Check if a block needs to be drawn
if(t > 0) {
//Get the block color
var c;
if(t == 1) //I type
c = 180; //Cyan
else if(t == 2) //J type
c = 240; //Blue
else if(t == 3) //L type
c = 40; //Orange
else if(t == 4) //O type
c = 60; //Yellow
else if(t == 5) //S type
c = 120; //Green
else if(t == 6) //T type
c = 280; //Purple
else //Z type
c = 0; //Red
//Convert game coordinaes to pixel coordinates
pixelX = x*20;
pixelY = (19-y)*20;
/**** Draw the center part of the block ****/
//Set the fill color using the supplied color
ctx.fillStyle = "hsl(" + c + ",100%,50%)";
//Create a filled rectangle
ctx.fillRect(pixelX+2,pixelY+2,16,16);
/**** Draw the top part of the block ****/
//Set the fill color slightly lighter
ctx.fillStyle = "hsl(" + c + ",100%,70%)";
//Create the top polygon and fill it
ctx.beginPath();
ctx.moveTo(pixelX,pixelY);
ctx.lineTo(pixelX+20,pixelY);
ctx.lineTo(pixelX+18,pixelY+2);
ctx.lineTo(pixelX+2,pixelY+2);
ctx.fill();
/**** Draw the sides of the block ****/
//Set the fill color slightly darker
ctx.fillStyle = "hsl(" + c + ",100%,40%)";
//Create the left polygon and fill it
ctx.beginPath();
ctx.moveTo(pixelX,pixelY);
ctx.lineTo(pixelX,pixelY+20);
ctx.lineTo(pixelX+2,pixelY+18);
ctx.lineTo(pixelX+2,pixelY+2);
ctx.fill();
//Create the right polygon and fill it
ctx.beginPath();
ctx.moveTo(pixelX+20,pixelY);
ctx.lineTo(pixelX+20,pixelY+20);
ctx.lineTo(pixelX+18,pixelY+18);
ctx.lineTo(pixelX+18,pixelY+2);
ctx.fill();
/**** Draw the bottom part of the block ****/
//Set the fill color much darker
ctx.fillStyle = "hsl(" + c + ",100%,30%)";
//Create the bottom polygon and fill it
ctx.beginPath();
ctx.moveTo(pixelX,pixelY+20);
ctx.lineTo(pixelX+20,pixelY+20);
ctx.lineTo(pixelX+18,pixelY+18);
ctx.lineTo(pixelX+2,pixelY+18);
ctx.fill();
}
}
/*************************************************
Draws a tetrimino at the specified game coordinate
with the specified orientation
x = [0,9] x-coordinate
y = [0,19] y-coordinate
t = [1,7] tetrimino type
o = [0,3] orientation
d = [-1,1] test, erase, or draw
*************************************************/
function drawTetrimino(x,y,t,o,d) {
//Determine the value to send to setGrid
c = -1;
if(d >= 0) c = t*d;
//Initialize validity test
valid = true;
/**** Pick the appropriate tetrimino type ****/
if(t == 1) { //I Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x+2,y,c);
}
else if(o == 1) {
valid = valid && setGrid(x+1,y+1,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x+1,y-1,c);
valid = valid && setGrid(x+1,y-2,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y-1,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x+1,y-1,c);
valid = valid && setGrid(x+2,y-1,c);
}
else if(o == 3) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x,y-2,c);
}
}
if(t == 2) { //J Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y+1,c);
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
}
else if(o == 1) {
valid = valid && setGrid(x+1,y+1,c);
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x+1,y-1,c);
}
else if(o == 3) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x-1,y-1,c);
}
}
if(t == 3) { //L Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x+1,y+1,c);
}
else if(o == 1) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x+1,y-1,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y-1,c);
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
}
else if(o == 3) {
valid = valid && setGrid(x-1,y+1,c);
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
}
}
if(t == 4) { //O Type
//Orientation doesn’t matter
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x+1,y+1,c);
}
if(t == 5) { //S Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x+1,y+1,c);
}
else if(o == 1) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x+1,y-1,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y-1,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
}
else if(o == 3) {
valid = valid && setGrid(x-1,y+1,c);
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
}
}
if(t == 6) { //T Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x,y+1,c);
}
else if(o == 1) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x+1,y,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x,y-1,c);
}
else if(o == 3) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x-1,y,c);
}
}
if(t == 7) { //Z Type
//Get orientation
if(o == 0) {
valid = valid && setGrid(x-1,y+1,c);
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x+1,y,c);
}
else if(o == 1) {
valid = valid && setGrid(x+1,y+1,c);
valid = valid && setGrid(x+1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
}
else if(o == 2) {
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x,y-1,c);
valid = valid && setGrid(x+1,y-1,c);
}
else if(o == 3) {
valid = valid && setGrid(x,y+1,c);
valid = valid && setGrid(x,y,c);
valid = valid && setGrid(x-1,y,c);
valid = valid && setGrid(x-1,y-1,c);
}
}
return valid;
}
/*************************************************
Sets a grid cell in the game state grid
x = [0,9] x-coordinate
y = [0,19] y-coordinate
t = [-1,7] test or block type
*************************************************/
function setGrid(x, y, t) {
//Check if point is in range
if(x >= 0 && x < 10 && y >= 0 && y < 20) {
//Return test result if testing
if(t < 0) return grid[y][x] == 0;
//Otherwise assign block type to the grid
grid[y][x] = t;
return true;
}
return false;
}
/*************************************************
Responds to a key press event
*************************************************/
function keyDown(e) {
if(e.keyCode == 37) { //Left arrow
drawTetrimino(x,y,t,o,0); //Erase the current tetrimino
x2 = x - 1;
if(drawTetrimino(x2,y,t,o,-1)) //Check if valid
x = x2;
}
else if(e.keyCode == 38) { //Up arrow
drawTetrimino(x,y,t,o,0); //Erase the current tetrimino
o2 = (o + 1) % 4;
if(drawTetrimino(x,y,t,o2,-1)) //Check if valid
o = o2;
}
else if(e.keyCode == 39) { //Right arrow
drawTetrimino(x,y,t,o,0); //Erase the current tetrimino
x2 = x + 1;
if(drawTetrimino(x2,y,t,o,-1)) //Check if valid
x = x2;
}
else if(e.keyCode == 40) { //Down arrow
drawTetrimino(x,y,t,o,0); //Erase the current tetrimino
y2 = y - 1;
if(drawTetrimino(x,y2,t,o,-1)) //Check if valid
y = y2;
}
else if(e.keyCode == 32) { //Space-bar
drawTetrimino(x,y,t,o,0); //Erase the current tetrimino
//Move down until invalid
while(drawTetrimino(x,y-1,t,o,-1))
y -= 1;
gameStep();
}
//Draw the current tetrimino
drawTetrimino(x,y,t,o,1);
//Redraw the grid
drawGrid();
}
/*************************************************
Updates the game state at regular intervals
*************************************************/
function gameStep() {
//Erase the current tetrimino
drawTetrimino(x,y,t,o,0);
//Check if the tetrimino can be dropped 1 block
y2 = y - 1;
if(drawTetrimino(x,y2,t,o,-1))
y = y2;
else {
//Redraw last tetrimino
drawTetrimino(x,y,t,o,1);
//Check if any lines are complete
checkLines();
//Create a new tetrimino
t2 = 1 + Math.floor((Math.random()*7));
x2 = 4;
y2 = 18;
o2 = 0;
//Check if valid
if(drawTetrimino(x2,y2,t2,o2,-1)) {
t = t2;
x = x2;
y = y2;
o = o2;
}
else {
alert("Game Over");
initialize();
return;
}
}
//Draw the current tetrimino
drawTetrimino(x,y,t,o,1);
//Redraw the grid
drawGrid();
}
/*************************************************
Removes completed lines from the grid
*************************************************/
function checkLines() {
//Loop over each line in the grid
for(i = 0; i < 20; i++) {
//Check if the line is full
full = true;
for(j = 0; j < 10; j++)
full = full && (grid[i][j] > 0);
if(full) {
//Loop over the remaining lines
for(ii = i; ii < 19; ii++) {
//Copy each line from the line above
for(j = 0; j < 10; j++)
grid[ii][j] = grid[ii+1][j];
}
//Make sure the top line is clear
for(j = 0; j < 10; j++)
grid[19][j] = 0;
//Repeat the check for this line
i--;
}
}
}
</script>
<body onload="initialize();" onkeydown="keyDown(event);" style="background-color:#EEEEEE">
<canvas id="myCanvas" height="400px" width="200px" style="background-color:#444444"></canvas>
<div style="width:200px;background-color:#CCCCCC">
Score: 0
</div>
</body>
</html>
And that’s it! The game should now be playable with game pieces that appear and fall automatically and lines that are cleared when they become full. Next time we’ll add the finishing touches that will make it fun to play, such as updating the score and increasing the speed as the game progresses.