UNPKG

nes-tetris-components

Version:

A set of components and front-end functionality of NES Tetris

71 lines (70 loc) 3.01 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const lodash_1 = __importDefault(require("lodash")); const nes_tetris_representation_1 = require("nes-tetris-representation"); const tetris_grid_1 = require("./tetris-grid"); ; ; class PlacePieces extends react_1.default.Component { constructor(props) { super(props); this.state = { currentPiece: this.props.activePiece === null ? null : this.getNewPiece(this.props.activePiece), }; this.keyDownHandler = this.keyDownHandler.bind(this); this.setPieceInPlace = this.setPieceInPlace.bind(this); this.getNewPiece = this.getNewPiece.bind(this); this.getBlockProps = this.getBlockProps.bind(this); } componentDidMount() { document.addEventListener('keydown', this.keyDownHandler); } componentWillUnmount() { document.removeEventListener('keydown', this.keyDownHandler); } keyDownHandler(event) { const currentPiece = this.props.inputHandler(event, this.state.currentPiece, this.props.grid, this.setPieceInPlace, this.getNewPiece, nes_tetris_representation_1.movePiece, this.props.disabled); if (currentPiece) { this.setState({ currentPiece }); } } setPieceInPlace() { const { grid } = this.props; const { currentPiece } = this.state; if (currentPiece !== null) { const newGrid = lodash_1.default.cloneDeep(grid); currentPiece.blocks.forEach(block => { newGrid[block.row][block.column] = block.value; }); const gridAfterPlaceBeforeClear = lodash_1.default.cloneDeep(newGrid); const completeRows = newGrid.map(row => row.every(block => !!block)); completeRows.forEach((isRowComplete, index) => { if (isRowComplete) { newGrid.splice(index, 1); newGrid.unshift(new Array(10).fill(0)); } }); this.props.setPiece(newGrid, gridAfterPlaceBeforeClear); } } getNewPiece(type) { return nes_tetris_representation_1.getPiece({ type, row: 2, column: 5, orientation: 0 }); } getBlockProps() { return { disabled: this.props.disabled }; } render() { const drawnGrid = lodash_1.default.cloneDeep(this.props.grid); if (this.state.currentPiece) { this.state.currentPiece.blocks.forEach(block => { drawnGrid[block.row][block.column] = block.value; }); } return react_1.default.createElement(tetris_grid_1.TetrisGrid, { grid: drawnGrid, getBlockProps: this.getBlockProps }); } } exports.default = PlacePieces;