1.0.2 • Published 5 years ago

classic-tetris-js v1.0.2

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

classic-tetris-js

An HTML5 + Javascript implementation of the popular game Tetris, classic-tetris-js takes after the older versions of the game, such as NES Tetris.

Play classic-tetris-js here!

Features

  • Supported inputs: keyboard, mouse, touch and stylus pen.
  • Starting level selection.
  • 'Play', 'Pause' and 'Quit' functions.
  • Additional game mechanics: Ghost piece and Hard drop.
  • Classic randomizer: 'Next' piece is randomly chosen with a slight bias against repeating pieces.
  • Customizable graphics and sound.
  • Powerful event system to notify in-game activity.

Quick start

Options to add classic-tetris-js to your project:

Basic setup

Include 'classic-tetris.js' in your HTML file.

<script src='classic-tetris.js'></script>

Add the game's HTML elements:

<canvas id='tetris-canvas' width='520' height='600'></canvas>
<div>
  <label for='level-input'>Start level:</label>
  <input id='level-input' name='level-input' type='number' min='0' max='19' value='5'></input>
  <button id='start-stop-btn'>Play/Pause</button>
  <button id='quit-btn'>Quit</button>
</div>

A canvas is required for the game to render. Besides that, it is convenient to also have a 'Start level' input, and buttons to play/pause and quit the game.

Finally, add the following script to initialize the game on window load:

window.addEventListener('load', event => {
  const canvas = document.getElementById('tetris-canvas');
  const tetris = new ClassicTetris(canvas);
  document.getElementById('start-stop-btn').addEventListener('click', event => {
    const startLevel = document.getElementById('level-input').value;
    tetris.setStartLevel(startLevel);
    tetris.togglePlayPause();
  });
  document.getElementById('quit-btn').addEventListener('click', event => {
    tetris.quit();
  });
});

A working example can be found in index.html.

Game controls

The player can control the game using the keyboard. The following table shows the action-to-keys mapping:

ActionKeys
Move piece leftLeft arrow, A
Move piece rightRight arrow, D
Move piece downDown arrow, S
Rotate piece clockwiseUp arrow, W, X, K
Rotate piece anticlockwiseZ, L
Hard dropSpace bar
PauseESC, P

The player can also control the game using pointer devices such as a mouse, a touch screen, or a stylus pen:

ActionPointer gesture
Move piece leftMove the pointer to the left of the piece
Move piece rightMove the pointer to the right of the piece
Move piece downPlace the pointer on the piece and move down
Rotate piece clockwiseClick / tap (left mouse button, touch contact, pen contact),wheel up
Rotate piece anticlockwiseClick / tap (mouse wheel, right mouse button, pen barrel button, X1 (back) mouse, X2 (forward) mouse, pen eraser button),wheel down

Customizing the game

It is also possible to specify default values for many of the game's parameters. This can be accomplished via the ClassicTetris constructor, which takes an options object after the required canvas element:

const tetris = new ClassicTetris(canvas, {
   boardWidth: 10,
   // ... additional parameters here
 });

Dimensions

The following parameters establish the size and location of the game board. Note that the canvas element will not be resized automatically, so its width and height attributes may need to be adjusted accordingly, as well the positioning of the HUD elements.

The recommended size for the canvas using default parameters is 520x600 pixels, as seen in the example above.

Parameter nameDescriptionDefault value
boardWidthWidth of the game board in terms of squares.10
boardHeightHeight of the game board in terms of squares. This value is the sum of: - Number of visible rows.- 2 invisible rows above the board, used to accomodate newly spawned pieces.22
boardXGame board's left edge relative to the canvas's left edge (in pixels).30
boardYGame board's top edge relative to the canvas's top edge (in pixels).Note that since the board's top 2 rows are invisible, but taken into account for coordinates calculation in the render, this value may be negative.-35
squareSideSide length of a square block (in pixels).28

Heads-Up Display

The HUD displays information about the ongoing game: score, lines and next piece. The positioning of these elements, as well as the text's font and color, may be specified using the parameters below:

Parameter nameDescriptionDefault value
canvasFontFont properties for the canvas (see HTML canvas font Property for more details).'17px georgia'
canvasFontColorFont color for the canvas (see HTML canvas fillStyle Property for more details).'#fff'
scoreXScore label's left edge relative to the canvas's left edge (in pixels).330
scoreYScore label's top edge relative to the canvas's top edge (in pixels).100
levelXLevel label's left edge relative to the canvas's left edge (in pixels).330
levelYLevel label's top edge relative to the canvas's top edge (in pixels).130
linesXLines label's left edge relative to the canvas's left edge (in pixels).330
linesYLines label's top edge relative to the canvas's top edge (in pixels).160
nextX'Next' label's left edge relative to the canvas's left edge (in pixels).330
nextY'Next' label's top edge relative to the canvas's top edge (in pixels).260
nextOffsetXNext piece's left edge relative to the canvas's left edge (in pixels).330
nextOffsetYNext piece's top edge relative to the canvas's top edge (in pixels).280
pauseX'Pause' label's left edge relative to the canvas's left edge (in pixels).145
pauseY'Pause' label's top edge relative to the canvas's top edge (in pixels).220

Colors

Color for the pieces is specified with a pair of values that determine the fill and border colors for the piece's individual squares (see HTML canvas fillStyle Property and HTML canvas strokeStyle Property for permitted for fill and border color values, respectively). Background and grid colors can also be changed.

Parameter nameDescriptionDefault value
zColorFill and border color for the Z piece's squares. '#fe103c', '#f890a7'
sColorFill and border color for the S piece's squares. '#66fd00', '#c4fe93'
oColorFill and border color for the O piece's squares. '#ffde00', '#fff88a'
lColorFill and border color for the L piece's squares. '#ff7308', '#ffca9b'
jColorFill and border color for the J piece's squares. '#1801ff', '#5a95ff'
tColorFill and border color for the T piece's squares. '#b802fd', '#f591fe'
iColorFill and border color for the I piece's squares. '#00e6fe', '#86fefe'
gameOverColorFill and border color for the squares that flood the board on game over. '#fff', '#ddd'
ghostColorFill and border color for the ghost piece's squares. '#000', '#fff'
backgroundColorGame board's background color.'#222'
tetrisBackgroundColorGame board's background color when burning a tetris.This color alternates with the default background color to create a flashing effect.'#fff'
borderColorGame board's border color.'#fff'
gridColorGame board's internal grid color.'#ddd'

Sound

Although no music or sound effects are provided by default, it is possible to set these by providing HTMLAudioElement objects:

const tetris = new ClassicTetris(canvas, {
  gameTheme: new Audio('korobeiniki.mp3'),
  // ... additional sound effects
});
Parameter nameDescriptionDefault value
rotateSoundPiece rotation sound.undefined
moveSoundLeft or right piece move sound.undefined
setSoundPlayed when a piece locks on.undefined
gameOverSoundPlayed on game overundefined
lineSoundSound of a single, double or triple line burn.undefined
tetrisSoundSound of a 4-line burnundefined
levelChangeSoundPlayed when the level increases.undefined
pauseSoundPlayed when pausing the game.undefined
gameThemeTheme song that plays throughout the game.Playback automatically pauses when the game pauses, and resumes when the game resumes.undefined

Pointer parameters

The purpose of these is to help recognize the click / tap gesture when using a pointer device to control the game.

Parameter nameDescriptionDefault value
tapClickMaxDistanceMaximum distance between pointer-down and pointer-up coordinates (in pixels) for the game to count it as a click / tap.10
tapClickMaxDurationMaximum duration of a click / tap (in ms) to be regarded as such.500

Functions

ClassicTetris provides the following functions to control the flow of the game.

Function nameDescriptionParameters
setStartLevelSet the starting level for the next game.Has no effect if invoked while a game is being played.level: an integer between 0 and 19
togglePlayPauseStarts a game if not playing, otherwise pauses/resumes the ongoing game.It is recommended to bind this method to the 'Play/Pause' button's click event, as shown in the 'Basic setup' example.none
quitIf playing, terminates the game.none
onAdds an event handler.event: name of the event (see table below),handler: callback function to be invoked when the event fires.
offRemoves an event handler.event: name of the event (see table below),handler: callback function to be removed.

Events

ClassicTetris dispatches events to notify about in-game occurrences. Event listeners will be passed a single data parameter with details about the event.

Event nameDescriptionEvent data object properties
ClassicTetris.GAME_STARTFired at the beginning of a game.type, level, score, lines
ClassicTetris.GAME_OVERFired at the end of a game.type, level, score, lines
ClassicTetris.GAME_OVER_STARTSignals the beginning of the game-over animation.type, level, score, lines
ClassicTetris.GAME_OVER_ENDSignals the end of the game-over animation.type, level, score, lines
ClassicTetris.GAME_PAUSEFired when the game pauses.type, level, score, lines
ClassicTetris.GAME_RESUMEFired when the game resumes after a pause.type, level, score, lines
ClassicTetris.PIECE_MOVE_LEFTFired when the current piece moves left.type, piece, rotation, oldPosition, newPosition
ClassicTetris.PIECE_MOVE_RIGHTFired when the current piece moves right.type, piece, rotation, oldPosition, newPosition
ClassicTetris.PIECE_MOVE_DOWNFired when the current piece moves down.type, piece, rotation, oldPosition, newPosition, downPressed
ClassicTetris.PIECE_HARD_DROPFired when the current piece is hard-dropped.type, piece, rotation, oldPosition, newPosition
ClassicTetris.PIECE_ROTATE_CLOCKWISEFired when the current piece rotates clockwise.type, piece, position, oldRotation, newRotation
ClassicTetris.PIECE_ROTATE_ANTICLOCKWISEFired when the current piece rotates anticlockwise.type, piece, position, oldRotation, newRotation
ClassicTetris.PIECE_LOCKFired when the current piece locks on.type, piece, rotation, position
ClassicTetris.NEXT_PIECEFired whenever a piece is generated.type, piece, nextPiece
ClassicTetris.LEVEL_CHANGEFired when the level changes.type, oldLevel, newLevel
ClassicTetris.SCORE_CHANGEFired when the score changes.type, oldScore, newScore
ClassicTetris.LINE_CLEAR_STARTSignals the start of the line-clear animation.type, linesBurnt
ClassicTetris.LINE_CLEAR_ENDSignals the end of the line-clear animation.type, linesBurnt
ClassicTetris.LINE_CLEARFired when one or more lines are cleared.type, oldLines, newLines

License

classic-tetris-js is released under the MIT License. See LICENSE for details.