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.
1 |
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.
1 2 3 4 5 6 7 8 9 |
//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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/************************************************* 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/************************************************* 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
<!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.