So far, we’ve only been creating static images with our drawing commands. The next step is to make the images move. Games demand some level of interactivity, so we need to be able to respond to user input. In Tetris, the user is able to move the current tetrimino to the left or right, adjust its orientation, or drop it down onto the stack. We’ll use the four arrow keys as the controls for our game. You may remember that we added an onload attribute to the <body> tag to call a JavaScript function as soon as the page is loaded. There are actually many different events that we can define for each element in the HTML document, and the one that we are currently interested in is the onkeydown event. This is fired whenever a key is pressed on the keyboard. We’ll create a new function to handle the event. Add the following attribute to the <body> tag:
1 |
onkeydown="keyDown(event);" |
In the <script> section, we will define the following function:
1 2 3 |
function keyDown(e) { alert("Keycode: " + e.keyCode"); } |
This function will display a popup window with a key code whenever we press a button. If we load the page and press the arrow keys, we should find that the key codes for left, up, right, and down arrow are 37, 38, 39, and 40 respectively. Now that we know the code that each key maps to, we can create an if-else block to take the appropriate action, based on which key was pressed. For our first test, we’ll create a random tetrimino and allow the user to move it around as if they were playing the game. We’ll need to add four global variables to keep track of the current tetrimino’s type, position, and orientation.
1 2 3 |
var t; //Tetrimino type var x, y; //Tetrimino position var o; //Tetrimino orientation |
Any time we add global variables, we should make sure they are initialized in the initialize function. Add the following lines to that function:
1 2 3 4 5 |
//Initialize tetrimino variables t = 0; x = 4; y = 18; o = 0; |
The left and right arrow keys should move the tetrimino one block left and right respectively. The up arrow key should change the orientation. For our game, the down key will eventually provide a hard drop, immediately placing the current tetrimino onto the stack, but for now, we’ll just move it down one block at a time. Change the function to 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 |
function keyDown(e) { //Clear the canvas ctx.clearRect(0,0,200,400); if(e.keyCode == 37) { //Left arrow x -= 1; } else if(e.keyCode == 38) { //Up arrow o = (o + 1) % 4; } else if(e.keyCode == 39) { //Right arrow x += 1; } else if(e.keyCode == 40) { //Down arrow y -= 1; } else { //Create a new tetrimino t = Math.floor((Math.random()*7)); x = 4; y = 18; o = 0; } //Draw the current tetrimino to the canvas drawTetrimino(x,y,t,o); } |
You can see that the first thing we do when a key is pressed is clear the canvas, giving us a clean slate to draw on. We then take the appropriate action, either updating the current coordinate or orientation, or creating a new tetrimino if a non-arrow key was pressed. The += and -= variable assignments increment or decrement the variable by the specified value. x += 1 is equivalent to x = x + 1 and y -= 1 is equivalent to y = y - 1. The % symbol used to change orientation is the modulus operator. This is essentially the remainder part of the result after division. In this case, the statement o = (o + 1) % 4 increments the o variable by 1, but resets it back to 0 if it gets up to 4. This keeps it in the valid range of 0 to 3.
When we create a new tetrimino, we use the built in JavaScript Math object to create a random number between 0 and 6 to represent the tetrimino type. The function Math.random() returns a uniformly sampled random number between 0 (inclusive) and 1 (exclusive), which we represent with the shorthand [0,1). By multiplying this value by 7 the output range becomes [0,7). To get an integer value, we use the Math.floor() function to trim off any fractional value and round down to the nearest whole number. This effectively gives us a random integer in the range 0 to 6 to represent the tetrimino type.
Lastly, we draw the current tetrimino to the canvas using the updated values. 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 |
<!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 /************************************************ 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 = 0; x = 4; y = 18; o = 0; } /************************************************ Draws a block at the specified game coordinate x = [0,9] x-coordinate y = [0,19] y-coordinate c = [0,360] color hue ************************************************/ function drawBlock(x, y, c) { //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 = [0,6] tetrimino type o = [0,3] orientation *************************************************/ function drawTetrimino(x,y,t,o) { /**** Pick the appropriate tetrimino type ****/ if(t == 0) { //I Type c = 180; //Cyan //Get orientation if(o == 0) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x+2,y,c); } else if(o == 1) { drawBlock(x+1,y+1,c); drawBlock(x+1,y,c); drawBlock(x+1,y-1,c); drawBlock(x+1,y-2,c); } else if(o == 2) { drawBlock(x-1,y-1,c); drawBlock(x,y-1,c); drawBlock(x+1,y-1,c); drawBlock(x+2,y-1,c); } else if(o == 3) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x,y-2,c); } } if(t == 1) { //J Type c = 240; //Blue //Get orientation if(o == 0) { drawBlock(x-1,y+1,c); drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); } else if(o == 1) { drawBlock(x+1,y+1,c); drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); } else if(o == 2) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x+1,y-1,c); } else if(o == 3) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x-1,y-1,c); } } if(t == 2) { //L Type c = 40; //Orange //Get orientation if(o == 0) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x+1,y+1,c); } else if(o == 1) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x+1,y-1,c); } else if(o == 2) { drawBlock(x-1,y-1,c); drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); } else if(o == 3) { drawBlock(x-1,y+1,c); drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); } } if(t == 3) { //O Type c = 60; //Yellow //Orientation doesn't matter drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x,y+1,c); drawBlock(x+1,y+1,c); } if(t == 4) { //S Type c = 120; //Green //Get orientation if(o == 0) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x,y+1,c); drawBlock(x+1,y+1,c); } else if(o == 1) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x+1,y-1,c); } else if(o == 2) { drawBlock(x-1,y-1,c); drawBlock(x,y-1,c); drawBlock(x,y,c); drawBlock(x+1,y,c); } else if(o == 3) { drawBlock(x-1,y+1,c); drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x,y-1,c); } } if(t == 5) { //T Type c = 280; //Purple //Get orientation if(o == 0) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x,y+1,c); } else if(o == 1) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x+1,y,c); } else if(o == 2) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x+1,y,c); drawBlock(x,y-1,c); } else if(o == 3) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x-1,y,c); } } if(t == 6) { //Z Type c = 0; //Red //Get orientation if(o == 0) { drawBlock(x-1,y+1,c); drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x+1,y,c); } else if(o == 1) { drawBlock(x+1,y+1,c); drawBlock(x+1,y,c); drawBlock(x,y,c); drawBlock(x,y-1,c); } else if(o == 2) { drawBlock(x-1,y,c); drawBlock(x,y,c); drawBlock(x,y-1,c); drawBlock(x+1,y-1,c); } else if(o == 3) { drawBlock(x,y+1,c); drawBlock(x,y,c); drawBlock(x-1,y,c); drawBlock(x-1,y-1,c); } } } /************************************************* Responds to a key press event *************************************************/ function keyDown(e) { //Clear the canvas ctx.clearRect(0,0,200,400); if(e.keyCode == 37) { //Left arrow x -= 1; } else if(e.keyCode == 38) { //Up arrow o = (o + 1) % 4; } else if(e.keyCode == 39) { //Right arrow x += 1; } else if(e.keyCode == 40) { //Down arrow y -= 1; } else { //Create a new tetrimino t = Math.floor((Math.random()*7)); x = 4; y = 18; o = 0; } //Draw the current tetrimino to the canvas drawTetrimino(x,y,t,o); } </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> |
If you run the code now and press a non-arrow key, you should see a random tetrimino appear at the top of the canvas. The arrow keys should allow you to move it left, right, and down, and pressing the up arrow key should change its orientation. You’ll notice that we haven’t implemented any boundary tests, so it’s easy to move the tetrimino all the way off the screen. We also have no good way of displaying more than one tetrimino at a time using this method, since we clear the entire canvas before redrawing the screen. The best way to fix this will be to implement a game state array that will maintain the current state of the game window. We can make changes to the array and then redraw its contents anytime a change occurs. Although this will incur some additional overhead for drawing single tetriminos, it will become very useful for implementing the game’s logic when many blocks are on the screen at once.