sketch.js - addyh/tetris GitHub Wiki

  • This is the main Javascript file where everything comes together
  • The entire game is implemented here
  • It defines the entire canvas, or "sketch"

Setup

setup()

  • Called one time, at page ready
  • Initializes Global Variables
    • board - Object of Board class
    • piece - Object of Piece class
    • mainCanvas - the Canvas we draw to
    • hiscoreInput - an Input box if they get the High Score
  • Other Globals:
    • gridSize - (default 50px) the pixel size of 1 block
    • gridWidth, gridHeight - (default 12) how many blocks wide/high is the grid?
    • function getBestName() - defined externally -- High score name
    • function getBestScore() - defined externally -- High score

Draw Loop

draw()

  • Called once every frame
  • Clears the screen
  • Then, re-draws the entire canvas
    • Including: game border, grid, current score, personal best

Start Screen

startScreen()

  • Called from draw() -- runs once every frame (if we are on the start screen)
  • (!gameStarted && !gameOver)
  • Draws the Start Screen
    • Start Game button
    • Current high score
    • Change Difficulty button

Game Over Screen

gameOverScreen()

  • Called from draw() -- runs once every frame (when the game is over)
  • (gameStarted && gameOver)
  • If player beat the High Score
    • Shows hiscoreInput for their name
    • Submit button to send new High Score
  • Else player did not beat High Score
    • Try Again
    • Change Difficulty

Main Game-Play Loop

gameLoop()

  • Called from draw() -- runs once every frame (during game-play itself)
  • (gameStarted && !gameOver)
  • Draws the current piece onto the board (piece.matrix) (4x4)
  • Draws all old pieces stacked onto the board (board.matrix) (12x12)
  • Calls piece.lower() to drop the piece by 1 block each frame
  • Handles keypresses