Improve Game files to match linter

This commit is contained in:
Arnaud Vergnet 2020-08-05 20:24:08 +02:00
parent 569e659779
commit cbe3777957
16 changed files with 1750 additions and 1610 deletions

View file

@ -1,13 +1,13 @@
// @flow
import type {CustomTheme} from "../../../managers/ThemeManager";
import type {CustomThemeType} from '../../../managers/ThemeManager';
export type Coordinates = {
export type CoordinatesType = {
x: number,
y: number,
}
};
type Shape = Array<Array<number>>;
export type ShapeType = Array<Array<number>>;
/**
* Abstract class used to represent a BaseShape.
@ -15,16 +15,18 @@ type Shape = Array<Array<number>>;
* and in methods to implement
*/
export default class BaseShape {
#currentShape: ShapeType;
#currentShape: Shape;
#rotation: number;
position: Coordinates;
theme: CustomTheme;
position: CoordinatesType;
theme: CustomThemeType;
/**
* Prevent instantiation if classname is BaseShape to force class to be abstract
*/
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
if (this.constructor === BaseShape)
throw new Error("Abstract class can't be instantiated");
this.theme = theme;
@ -37,6 +39,7 @@ export default class BaseShape {
* Gets this shape's color.
* Must be implemented by child class
*/
// eslint-disable-next-line class-methods-use-this
getColor(): string {
throw new Error("Method 'getColor()' must be implemented");
}
@ -47,14 +50,15 @@ export default class BaseShape {
*
* Used by tests to read private fields
*/
getShapes(): Array<Shape> {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
throw new Error("Method 'getShapes()' must be implemented");
}
/**
* Gets this object's current shape.
*/
getCurrentShape(): Shape {
getCurrentShape(): ShapeType {
return this.#currentShape;
}
@ -63,17 +67,20 @@ export default class BaseShape {
* This will return an array of coordinates representing the positions of the cells used by this object.
*
* @param isAbsolute Should we take into account the current position of the object?
* @return {Array<Coordinates>} This object cells coordinates
* @return {Array<CoordinatesType>} This object cells coordinates
*/
getCellsCoordinates(isAbsolute: boolean): Array<Coordinates> {
let coordinates = [];
for (let row = 0; row < this.#currentShape.length; row++) {
for (let col = 0; col < this.#currentShape[row].length; col++) {
if (this.#currentShape[row][col] === 1)
if (isAbsolute)
coordinates.push({x: this.position.x + col, y: this.position.y + row});
else
coordinates.push({x: col, y: row});
getCellsCoordinates(isAbsolute: boolean): Array<CoordinatesType> {
const coordinates = [];
for (let row = 0; row < this.#currentShape.length; row += 1) {
for (let col = 0; col < this.#currentShape[row].length; col += 1) {
if (this.#currentShape[row][col] === 1) {
if (isAbsolute) {
coordinates.push({
x: this.position.x + col,
y: this.position.y + row,
});
} else coordinates.push({x: col, y: row});
}
}
}
return coordinates;
@ -85,14 +92,10 @@ export default class BaseShape {
* @param isForward Should we rotate clockwise?
*/
rotate(isForward: boolean) {
if (isForward)
this.#rotation++;
else
this.#rotation--;
if (this.#rotation > 3)
this.#rotation = 0;
else if (this.#rotation < 0)
this.#rotation = 3;
if (isForward) this.#rotation += 1;
else this.#rotation -= 1;
if (this.#rotation > 3) this.#rotation = 0;
else if (this.#rotation < 0) this.#rotation = 3;
this.#currentShape = this.getShapes()[this.#rotation];
}
@ -106,5 +109,4 @@ export default class BaseShape {
this.position.x += x;
this.position.y += y;
}
}

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeI extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeI extends BaseShape {
return this.theme.colors.tetrisI;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[0, 0, 0, 0],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeJ extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeJ extends BaseShape {
return this.theme.colors.tetrisJ;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[1, 0, 0],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeL extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeL extends BaseShape {
return this.theme.colors.tetrisL;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[0, 0, 1],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeO extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 4;
}
@ -14,7 +14,8 @@ export default class ShapeO extends BaseShape {
return this.theme.colors.tetrisO;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[1, 1],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeS extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeS extends BaseShape {
return this.theme.colors.tetrisS;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[0, 1, 1],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeT extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeT extends BaseShape {
return this.theme.colors.tetrisT;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[0, 1, 0],

View file

@ -1,11 +1,11 @@
// @flow
import BaseShape from "./BaseShape";
import type {CustomTheme} from "../../../managers/ThemeManager";
import BaseShape from './BaseShape';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeZ extends BaseShape {
constructor(theme: CustomTheme) {
constructor(theme: CustomThemeType) {
super(theme);
this.position.x = 3;
}
@ -14,7 +14,8 @@ export default class ShapeZ extends BaseShape {
return this.theme.colors.tetrisZ;
}
getShapes() {
// eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [
[
[1, 1, 0],

View file

@ -3,19 +3,17 @@
import * as React from 'react';
import {View} from 'react-native';
import {withTheme} from 'react-native-paper';
import type {CustomTheme} from "../../../managers/ThemeManager";
export type Cell = {color: string, isEmpty: boolean, key: string};
export type CellType = {color: string, isEmpty: boolean, key: string};
type Props = {
cell: Cell,
theme: CustomTheme,
}
type PropsType = {
cell: CellType,
};
class CellComponent extends React.PureComponent<Props> {
render() {
const item = this.props.cell;
class CellComponent extends React.PureComponent<PropsType> {
render(): React.Node {
const {props} = this;
const item = props.cell;
return (
<View
style={{
@ -29,8 +27,6 @@ class CellComponent extends React.PureComponent<Props> {
/>
);
}
}
export default withTheme(CellComponent);

View file

@ -3,51 +3,50 @@
import * as React from 'react';
import {View} from 'react-native';
import {withTheme} from 'react-native-paper';
import type {Cell} from "./CellComponent";
import CellComponent from "./CellComponent";
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
import type {CellType} from './CellComponent';
import CellComponent from './CellComponent';
export type Grid = Array<Array<CellComponent>>;
export type GridType = Array<Array<CellComponent>>;
type Props = {
grid: Array<Array<Object>>,
type PropsType = {
grid: Array<Array<CellType>>,
height: number,
width: number,
style: ViewStyle,
}
};
class GridComponent extends React.Component<Props> {
getRow(rowNumber: number) {
let cells = this.props.grid[rowNumber].map(this.getCellRender);
class GridComponent extends React.Component<PropsType> {
getRow(rowNumber: number): React.Node {
const {grid} = this.props;
return (
<View
style={{flexDirection: 'row',}}
key={rowNumber.toString()}
>
{cells}
<View style={{flexDirection: 'row'}} key={rowNumber.toString()}>
{grid[rowNumber].map(this.getCellRender)}
</View>
);
}
getCellRender = (item: Cell) => {
return <CellComponent cell={item} key={item.key}/>;
getCellRender = (item: CellType): React.Node => {
return <CellComponent cell={item} key={item.key} />;
};
getGrid() {
let rows = [];
for (let i = 0; i < this.props.height; i++) {
getGrid(): React.Node {
const {height} = this.props;
const rows = [];
for (let i = 0; i < height; i += 1) {
rows.push(this.getRow(i));
}
return rows;
}
render() {
render(): React.Node {
const {style, width, height} = this.props;
return (
<View style={{
aspectRatio: this.props.width / this.props.height,
<View
style={{
aspectRatio: width / height,
borderRadius: 4,
...this.props.style
...style,
}}>
{this.getGrid()}
</View>

View file

@ -3,27 +3,28 @@
import * as React from 'react';
import {View} from 'react-native';
import {withTheme} from 'react-native-paper';
import type {Grid} from "./GridComponent";
import GridComponent from "./GridComponent";
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
import type {GridType} from './GridComponent';
import GridComponent from './GridComponent';
type Props = {
items: Array<Grid>,
style: ViewStyle
}
type PropsType = {
items: Array<GridType>,
style: ViewStyle,
};
class Preview extends React.PureComponent<Props> {
getGrids() {
let grids = [];
for (let i = 0; i < this.props.items.length; i++) {
grids.push(this.getGridRender(this.props.items[i], i));
}
class Preview extends React.PureComponent<PropsType> {
getGrids(): React.Node {
const {items} = this.props;
const grids = [];
items.forEach((item: GridType, index: number) => {
grids.push(Preview.getGridRender(item, index));
});
return grids;
}
getGridRender(item: Grid, index: number) {
return <GridComponent
static getGridRender(item: GridType, index: number): React.Node {
return (
<GridComponent
width={item[0].length}
height={item.length}
grid={item}
@ -33,21 +34,17 @@ class Preview extends React.PureComponent<Props> {
marginBottom: 5,
}}
key={index.toString()}
/>;
};
render() {
if (this.props.items.length > 0) {
return (
<View style={this.props.style}>
{this.getGrids()}
</View>
/>
);
} else
return null;
}
render(): React.Node {
const {style, items} = this.props;
if (items.length > 0) {
return <View style={style}>{this.getGrids()}</View>;
}
return null;
}
}
export default withTheme(Preview);

View file

@ -1,243 +1,318 @@
// @flow
import Piece from "./Piece";
import ScoreManager from "./ScoreManager";
import GridManager from "./GridManager";
import type {CustomTheme} from "../../../managers/ThemeManager";
import Piece from './Piece';
import ScoreManager from './ScoreManager';
import GridManager from './GridManager';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {GridType} from '../components/GridComponent';
export type TickCallbackType = (
score: number,
level: number,
grid: GridType,
) => void;
export type ClockCallbackType = (time: number) => void;
export type EndCallbackType = (
time: number,
score: number,
isRestart: boolean,
) => void;
export type MovementCallbackType = (grid: GridType, score?: number) => void;
export default class GameLogic {
static levelTicks = [1000, 800, 600, 400, 300, 200, 150, 100];
static levelTicks = [
1000,
800,
600,
400,
300,
200,
150,
100,
];
scoreManager: ScoreManager;
#scoreManager: ScoreManager;
#gridManager: GridManager;
gridManager: GridManager;
#height: number;
#width: number;
height: number;
#gameRunning: boolean;
#gamePaused: boolean;
#gameTime: number;
width: number;
#currentObject: Piece;
gameRunning: boolean;
#gameTick: number;
#gameTickInterval: IntervalID;
#gameTimeInterval: IntervalID;
gamePaused: boolean;
#pressInInterval: TimeoutID;
#isPressedIn: boolean;
#autoRepeatActivationDelay: number;
#autoRepeatDelay: number;
gameTime: number;
#nextPieces: Array<Piece>;
#nextPiecesCount: number;
currentObject: Piece;
#onTick: Function;
#onClock: Function;
endCallback: Function;
gameTick: number;
#theme: CustomTheme;
gameTickInterval: IntervalID;
constructor(height: number, width: number, theme: CustomTheme) {
this.#height = height;
this.#width = width;
this.#gameRunning = false;
this.#gamePaused = false;
this.#theme = theme;
this.#autoRepeatActivationDelay = 300;
this.#autoRepeatDelay = 50;
this.#nextPieces = [];
this.#nextPiecesCount = 3;
this.#scoreManager = new ScoreManager();
this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#theme);
gameTimeInterval: IntervalID;
pressInInterval: TimeoutID;
isPressedIn: boolean;
autoRepeatActivationDelay: number;
autoRepeatDelay: number;
nextPieces: Array<Piece>;
nextPiecesCount: number;
tickCallback: TickCallbackType;
clockCallback: ClockCallbackType;
endCallback: EndCallbackType;
theme: CustomThemeType;
constructor(height: number, width: number, theme: CustomThemeType) {
this.height = height;
this.width = width;
this.gameRunning = false;
this.gamePaused = false;
this.theme = theme;
this.autoRepeatActivationDelay = 300;
this.autoRepeatDelay = 50;
this.nextPieces = [];
this.nextPiecesCount = 3;
this.scoreManager = new ScoreManager();
this.gridManager = new GridManager(
this.getWidth(),
this.getHeight(),
this.theme,
);
}
getHeight(): number {
return this.#height;
return this.height;
}
getWidth(): number {
return this.#width;
return this.width;
}
getCurrentGrid() {
return this.#gridManager.getCurrentGrid();
}
isGameRunning(): boolean {
return this.#gameRunning;
getCurrentGrid(): GridType {
return this.gridManager.getCurrentGrid();
}
isGamePaused(): boolean {
return this.#gamePaused;
return this.gamePaused;
}
onFreeze() {
this.#gridManager.freezeTetromino(this.#currentObject, this.#scoreManager);
onFreeze = () => {
this.gridManager.freezeTetromino(this.currentObject, this.scoreManager);
this.createTetromino();
}
};
setNewGameTick(level: number) {
if (level >= GameLogic.levelTicks.length)
return;
this.#gameTick = GameLogic.levelTicks[level];
clearInterval(this.#gameTickInterval);
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick);
if (level >= GameLogic.levelTicks.length) return;
this.gameTick = GameLogic.levelTicks[level];
this.stopTick();
this.startTick();
}
onTick(callback: Function) {
this.#currentObject.tryMove(0, 1,
this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(),
() => this.onFreeze());
startClock() {
this.gameTimeInterval = setInterval(() => {
this.onClock(this.clockCallback);
}, 1000);
}
startTick() {
this.gameTickInterval = setInterval(() => {
this.onTick(this.tickCallback);
}, this.gameTick);
}
stopClock() {
clearInterval(this.gameTimeInterval);
}
stopTick() {
clearInterval(this.gameTickInterval);
}
stopGameTime() {
this.stopClock();
this.stopTick();
}
startGameTime() {
this.startClock();
this.startTick();
}
onTick(callback: TickCallbackType) {
this.currentObject.tryMove(
0,
1,
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
this.onFreeze,
);
callback(
this.#scoreManager.getScore(),
this.#scoreManager.getLevel(),
this.#gridManager.getCurrentGrid());
if (this.#scoreManager.canLevelUp())
this.setNewGameTick(this.#scoreManager.getLevel());
this.scoreManager.getScore(),
this.scoreManager.getLevel(),
this.gridManager.getCurrentGrid(),
);
if (this.scoreManager.canLevelUp())
this.setNewGameTick(this.scoreManager.getLevel());
}
onClock(callback: Function) {
this.#gameTime++;
callback(this.#gameTime);
onClock(callback: ClockCallbackType) {
this.gameTime += 1;
callback(this.gameTime);
}
canUseInput() {
return this.#gameRunning && !this.#gamePaused
canUseInput(): boolean {
return this.gameRunning && !this.gamePaused;
}
rightPressed(callback: Function) {
this.#isPressedIn = true;
rightPressed(callback: MovementCallbackType) {
this.isPressedIn = true;
this.movePressedRepeat(true, callback, 1, 0);
}
leftPressedIn(callback: Function) {
this.#isPressedIn = true;
leftPressedIn(callback: MovementCallbackType) {
this.isPressedIn = true;
this.movePressedRepeat(true, callback, -1, 0);
}
downPressedIn(callback: Function) {
this.#isPressedIn = true;
downPressedIn(callback: MovementCallbackType) {
this.isPressedIn = true;
this.movePressedRepeat(true, callback, 0, 1);
}
movePressedRepeat(isInitial: boolean, callback: Function, x: number, y: number) {
if (!this.canUseInput() || !this.#isPressedIn)
return;
const moved = this.#currentObject.tryMove(x, y,
this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(),
() => this.onFreeze());
movePressedRepeat(
isInitial: boolean,
callback: MovementCallbackType,
x: number,
y: number,
) {
if (!this.canUseInput() || !this.isPressedIn) return;
const moved = this.currentObject.tryMove(
x,
y,
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
this.onFreeze,
);
if (moved) {
if (y === 1) {
this.#scoreManager.incrementScore();
callback(this.#gridManager.getCurrentGrid(), this.#scoreManager.getScore());
} else
callback(this.#gridManager.getCurrentGrid());
this.scoreManager.incrementScore();
callback(
this.gridManager.getCurrentGrid(),
this.scoreManager.getScore(),
);
} else callback(this.gridManager.getCurrentGrid());
}
this.#pressInInterval = setTimeout(() =>
this.movePressedRepeat(false, callback, x, y),
isInitial ? this.#autoRepeatActivationDelay : this.#autoRepeatDelay
this.pressInInterval = setTimeout(
() => {
this.movePressedRepeat(false, callback, x, y);
},
isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay,
);
}
pressedOut() {
this.#isPressedIn = false;
clearTimeout(this.#pressInInterval);
this.isPressedIn = false;
clearTimeout(this.pressInInterval);
}
rotatePressed(callback: Function) {
if (!this.canUseInput())
return;
rotatePressed(callback: MovementCallbackType) {
if (!this.canUseInput()) return;
if (this.#currentObject.tryRotate(this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight()))
callback(this.#gridManager.getCurrentGrid());
if (
this.currentObject.tryRotate(
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
)
)
callback(this.gridManager.getCurrentGrid());
}
getNextPiecesPreviews() {
let finalArray = [];
for (let i = 0; i < this.#nextPieces.length; i++) {
const gridSize = this.#nextPieces[i].getCurrentShape().getCurrentShape()[0].length;
finalArray.push(this.#gridManager.getEmptyGrid(gridSize, gridSize));
this.#nextPieces[i].toGrid(finalArray[i], true);
getNextPiecesPreviews(): Array<GridType> {
const finalArray = [];
for (let i = 0; i < this.nextPieces.length; i += 1) {
const gridSize = this.nextPieces[i].getCurrentShape().getCurrentShape()[0]
.length;
finalArray.push(this.gridManager.getEmptyGrid(gridSize, gridSize));
this.nextPieces[i].toGrid(finalArray[i], true);
}
return finalArray;
}
recoverNextPiece() {
this.#currentObject = this.#nextPieces.shift();
this.currentObject = this.nextPieces.shift();
this.generateNextPieces();
}
generateNextPieces() {
while (this.#nextPieces.length < this.#nextPiecesCount) {
this.#nextPieces.push(new Piece(this.#theme));
while (this.nextPieces.length < this.nextPiecesCount) {
this.nextPieces.push(new Piece(this.theme));
}
}
createTetromino() {
this.pressedOut();
this.recoverNextPiece();
if (!this.#currentObject.isPositionValid(this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight()))
if (
!this.currentObject.isPositionValid(
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
)
)
this.endGame(false);
}
togglePause() {
if (!this.#gameRunning)
return;
this.#gamePaused = !this.#gamePaused;
if (this.#gamePaused) {
clearInterval(this.#gameTickInterval);
clearInterval(this.#gameTimeInterval);
} else {
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick);
this.#gameTimeInterval = setInterval(this.#onClock, 1000);
}
}
stopGame() {
this.#gameRunning = false;
this.#gamePaused = false;
clearInterval(this.#gameTickInterval);
clearInterval(this.#gameTimeInterval);
if (!this.gameRunning) return;
this.gamePaused = !this.gamePaused;
if (this.gamePaused) this.stopGameTime();
else this.startGameTime();
}
endGame(isRestart: boolean) {
this.stopGame();
this.endCallback(this.#gameTime, this.#scoreManager.getScore(), isRestart);
this.gameRunning = false;
this.gamePaused = false;
this.stopGameTime();
this.endCallback(this.gameTime, this.scoreManager.getScore(), isRestart);
}
startGame(tickCallback: Function, clockCallback: Function, endCallback: Function) {
if (this.#gameRunning)
this.endGame(true);
this.#gameRunning = true;
this.#gamePaused = false;
this.#gameTime = 0;
this.#scoreManager = new ScoreManager();
this.#gameTick = GameLogic.levelTicks[this.#scoreManager.getLevel()];
this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#theme);
this.#nextPieces = [];
startGame(
tickCallback: TickCallbackType,
clockCallback: ClockCallbackType,
endCallback: EndCallbackType,
) {
if (this.gameRunning) this.endGame(true);
this.gameRunning = true;
this.gamePaused = false;
this.gameTime = 0;
this.scoreManager = new ScoreManager();
this.gameTick = GameLogic.levelTicks[this.scoreManager.getLevel()];
this.gridManager = new GridManager(
this.getWidth(),
this.getHeight(),
this.theme,
);
this.nextPieces = [];
this.generateNextPieces();
this.createTetromino();
tickCallback(
this.#scoreManager.getScore(),
this.#scoreManager.getLevel(),
this.#gridManager.getCurrentGrid());
clockCallback(this.#gameTime);
this.#onTick = this.onTick.bind(this, tickCallback);
this.#onClock = this.onClock.bind(this, clockCallback);
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick);
this.#gameTimeInterval = setInterval(this.#onClock, 1000);
this.scoreManager.getScore(),
this.scoreManager.getLevel(),
this.gridManager.getCurrentGrid(),
);
clockCallback(this.gameTime);
this.startTick();
this.startClock();
this.tickCallback = tickCallback;
this.clockCallback = clockCallback;
this.endCallback = endCallback;
}
}

View file

@ -1,19 +1,19 @@
// @flow
import Piece from "./Piece";
import ScoreManager from "./ScoreManager";
import type {Coordinates} from '../Shapes/BaseShape';
import type {Grid} from "../components/GridComponent";
import type {Cell} from "../components/CellComponent";
import type {CustomTheme} from "../../../managers/ThemeManager";
import Piece from './Piece';
import ScoreManager from './ScoreManager';
import type {CoordinatesType} from '../Shapes/BaseShape';
import type {GridType} from '../components/GridComponent';
import type {CellType} from '../components/CellComponent';
import type {CustomThemeType} from '../../../managers/ThemeManager';
/**
* Class used to manage the game grid
*/
export default class GridManager {
#currentGrid: GridType;
#currentGrid: Grid;
#theme: CustomTheme;
#theme: CustomThemeType;
/**
* Initializes a grid of the given size
@ -22,7 +22,7 @@ export default class GridManager {
* @param height The grid height
* @param theme Object containing current theme
*/
constructor(width: number, height: number, theme: CustomTheme) {
constructor(width: number, height: number, theme: CustomThemeType) {
this.#theme = theme;
this.#currentGrid = this.getEmptyGrid(height, width);
}
@ -30,9 +30,9 @@ export default class GridManager {
/**
* Get the current grid
*
* @return {Grid} The current grid
* @return {GridType} The current grid
*/
getCurrentGrid(): Grid {
getCurrentGrid(): GridType {
return this.#currentGrid;
}
@ -40,11 +40,11 @@ export default class GridManager {
* Get a new empty grid line of the given size
*
* @param width The line size
* @return {Array<Cell>}
* @return {Array<CellType>}
*/
getEmptyLine(width: number): Array<Cell> {
let line = [];
for (let col = 0; col < width; col++) {
getEmptyLine(width: number): Array<CellType> {
const line = [];
for (let col = 0; col < width; col += 1) {
line.push({
color: this.#theme.colors.tetrisBackground,
isEmpty: true,
@ -59,11 +59,11 @@ export default class GridManager {
*
* @param width The grid width
* @param height The grid height
* @return {Grid} A new empty grid
* @return {GridType} A new empty grid
*/
getEmptyGrid(height: number, width: number): Grid {
let grid = [];
for (let row = 0; row < height; row++) {
getEmptyGrid(height: number, width: number): GridType {
const grid = [];
for (let row = 0; row < height; row += 1) {
grid.push(this.getEmptyLine(width));
}
return grid;
@ -78,7 +78,7 @@ export default class GridManager {
*/
clearLines(lines: Array<number>, scoreManager: ScoreManager) {
lines.sort();
for (let i = 0; i < lines.length; i++) {
for (let i = 0; i < lines.length; i += 1) {
this.#currentGrid.splice(lines[i], 1);
this.#currentGrid.unshift(this.getEmptyLine(this.#currentGrid[0].length));
}
@ -92,18 +92,17 @@ export default class GridManager {
* @param pos The piece's coordinates to check lines at
* @return {Array<number>} An array containing the line numbers to clear
*/
getLinesToClear(pos: Array<Coordinates>): Array<number> {
let rows = [];
for (let i = 0; i < pos.length; i++) {
getLinesToClear(pos: Array<CoordinatesType>): Array<number> {
const rows = [];
for (let i = 0; i < pos.length; i += 1) {
let isLineFull = true;
for (let col = 0; col < this.#currentGrid[pos[i].y].length; col++) {
for (let col = 0; col < this.#currentGrid[pos[i].y].length; col += 1) {
if (this.#currentGrid[pos[i].y][col].isEmpty) {
isLineFull = false;
break;
}
}
if (isLineFull && rows.indexOf(pos[i].y) === -1)
rows.push(pos[i].y);
if (isLineFull && rows.indexOf(pos[i].y) === -1) rows.push(pos[i].y);
}
return rows;
}
@ -115,6 +114,9 @@ export default class GridManager {
* @param scoreManager A reference to the score manager
*/
freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) {
this.clearLines(this.getLinesToClear(currentObject.getCoordinates()), scoreManager);
this.clearLines(
this.getLinesToClear(currentObject.getCoordinates()),
scoreManager,
);
}
}

View file

@ -4,11 +4,12 @@
* Class used to manage game score
*/
export default class ScoreManager {
#scoreLinesModifier = [40, 100, 300, 1200];
#score: number;
#level: number;
#levelProgression: number;
/**
@ -51,7 +52,7 @@ export default class ScoreManager {
* Increments the score by one
*/
incrementScore() {
this.#score++;
this.#score += 1;
}
/**
@ -63,9 +64,9 @@ export default class ScoreManager {
* @param numberRemoved The number of lines removed at the same time
*/
addLinesRemovedPoints(numberRemoved: number) {
if (numberRemoved < 1 || numberRemoved > 4)
return;
this.#score += this.#scoreLinesModifier[numberRemoved-1] * (this.#level + 1);
if (numberRemoved < 1 || numberRemoved > 4) return;
this.#score +=
this.#scoreLinesModifier[numberRemoved - 1] * (this.#level + 1);
switch (numberRemoved) {
case 1:
this.#levelProgression += 1;
@ -79,6 +80,8 @@ export default class ScoreManager {
case 4: // Did a tetris !
this.#levelProgression += 8;
break;
default:
break;
}
}
@ -89,13 +92,12 @@ export default class ScoreManager {
*
* @return {boolean} True if the current level has changed
*/
canLevelUp() {
let canLevel = this.#levelProgression > this.#level * 5;
if (canLevel){
canLevelUp(): boolean {
const canLevel = this.#levelProgression > this.#level * 5;
if (canLevel) {
this.#levelProgression -= this.#level * 5;
this.#level++;
this.#level += 1;
}
return canLevel;
}
}

View file

@ -3,27 +3,28 @@
import * as React from 'react';
import {View} from 'react-native';
import {Caption, IconButton, Text, withTheme} from 'react-native-paper';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import GameLogic from "../logic/GameLogic";
import type {Grid} from "../components/GridComponent";
import GridComponent from "../components/GridComponent";
import Preview from "../components/Preview";
import i18n from "i18n-js";
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../../managers/ThemeManager";
import type {OptionsDialogButton} from "../../../components/Dialogs/OptionsDialog";
import OptionsDialog from "../../../components/Dialogs/OptionsDialog";
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import i18n from 'i18n-js';
import {StackNavigationProp} from '@react-navigation/stack';
import GameLogic from '../logic/GameLogic';
import type {GridType} from '../components/GridComponent';
import GridComponent from '../components/GridComponent';
import Preview from '../components/Preview';
import MaterialHeaderButtons, {
Item,
} from '../../../components/Overrides/CustomHeaderButton';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {OptionsDialogButtonType} from '../../../components/Dialogs/OptionsDialog';
import OptionsDialog from '../../../components/Dialogs/OptionsDialog';
type Props = {
type PropsType = {
navigation: StackNavigationProp,
route: { params: { highScore: number }, ... },
theme: CustomTheme,
}
route: {params: {highScore: number}},
theme: CustomThemeType,
};
type State = {
grid: Grid,
gameRunning: boolean,
type StateType = {
grid: GridType,
gameTime: number,
gameScore: number,
gameLevel: number,
@ -31,101 +32,320 @@ type State = {
dialogVisible: boolean,
dialogTitle: string,
dialogMessage: string,
dialogButtons: Array<OptionsDialogButton>,
dialogButtons: Array<OptionsDialogButtonType>,
onDialogDismiss: () => void,
}
};
class GameMainScreen extends React.Component<Props, State> {
class GameMainScreen extends React.Component<PropsType, StateType> {
static getFormattedTime(seconds: number): string {
const date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(seconds);
let format;
if (date.getHours())
format = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
else if (date.getMinutes())
format = `${date.getMinutes()}:${date.getSeconds()}`;
else format = date.getSeconds().toString();
return format;
}
logic: GameLogic;
highScore: number | null;
constructor(props) {
constructor(props: PropsType) {
super(props);
this.logic = new GameLogic(20, 10, this.props.theme);
this.logic = new GameLogic(20, 10, props.theme);
this.state = {
grid: this.logic.getCurrentGrid(),
gameRunning: false,
gameTime: 0,
gameScore: 0,
gameLevel: 0,
dialogVisible: false,
dialogTitle: "",
dialogMessage: "",
dialogTitle: '',
dialogMessage: '',
dialogButtons: [],
onDialogDismiss: () => {
},
onDialogDismiss: () => {},
};
if (this.props.route.params != null)
this.highScore = this.props.route.params.highScore;
if (props.route.params != null)
this.highScore = props.route.params.highScore;
}
componentDidMount() {
this.props.navigation.setOptions({
const {navigation} = this.props;
navigation.setOptions({
headerRight: this.getRightButton,
});
this.startGame();
}
componentWillUnmount() {
this.logic.stopGame();
this.logic.endGame(false);
}
getRightButton = () => {
return <MaterialHeaderButtons>
<Item title="pause" iconName="pause" onPress={this.togglePause}/>
</MaterialHeaderButtons>;
}
getRightButton = (): React.Node => {
return (
<MaterialHeaderButtons>
<Item title="pause" iconName="pause" onPress={this.togglePause} />
</MaterialHeaderButtons>
);
};
getFormattedTime(seconds: number) {
let date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(seconds);
let format;
if (date.getHours())
format = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
else if (date.getMinutes())
format = date.getMinutes() + ':' + date.getSeconds();
else
format = date.getSeconds();
return format;
}
onTick = (score: number, level: number, newGrid: Grid) => {
onTick = (score: number, level: number, newGrid: GridType) => {
this.setState({
gameScore: score,
gameLevel: level,
grid: newGrid,
});
}
};
onClock = (time: number) => {
this.setState({
gameTime: time,
});
}
};
updateGrid = (newGrid: Grid) => {
this.setState({
grid: newGrid,
});
}
onDialogDismiss = () => {
this.setState({dialogVisible: false});
};
updateGridScore = (newGrid: Grid, score: number) => {
onGameEnd = (time: number, score: number, isRestart: boolean) => {
const {props, state} = this;
this.setState({
grid: newGrid,
gameTime: time,
gameScore: score,
});
if (!isRestart)
props.navigation.replace('game-start', {
score: state.gameScore,
level: state.gameLevel,
time: state.gameTime,
});
};
getStatusIcons(): React.Node {
const {props, state} = this;
return (
<View
style={{
flex: 1,
marginTop: 'auto',
marginBottom: 'auto',
}}>
<View
style={{
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Caption
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 5,
}}>
{i18n.t('screens.game.time')}
</Caption>
<View
style={{
flexDirection: 'row',
}}>
<MaterialCommunityIcons
name="timer"
color={props.theme.colors.subtitle}
size={20}
/>
<Text
style={{
marginLeft: 5,
color: props.theme.colors.subtitle,
}}>
{GameMainScreen.getFormattedTime(state.gameTime)}
</Text>
</View>
</View>
<View
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 20,
}}>
<Caption
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 5,
}}>
{i18n.t('screens.game.level')}
</Caption>
<View
style={{
flexDirection: 'row',
}}>
<MaterialCommunityIcons
name="gamepad-square"
color={props.theme.colors.text}
size={20}
/>
<Text
style={{
marginLeft: 5,
}}>
{state.gameLevel}
</Text>
</View>
</View>
</View>
);
}
getScoreIcon(): React.Node {
const {props, state} = this;
const highScore =
this.highScore == null || state.gameScore > this.highScore
? state.gameScore
: this.highScore;
return (
<View
style={{
marginTop: 10,
marginBottom: 10,
}}>
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Text
style={{
marginLeft: 5,
fontSize: 20,
}}>
{i18n.t('screens.game.score', {score: state.gameScore})}
</Text>
<MaterialCommunityIcons
name="star"
color={props.theme.colors.tetrisScore}
size={20}
style={{
marginTop: 'auto',
marginBottom: 'auto',
marginLeft: 5,
}}
/>
</View>
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 5,
}}>
<Text
style={{
marginLeft: 5,
fontSize: 10,
color: props.theme.colors.textDisabled,
}}>
{i18n.t('screens.game.highScore', {score: highScore})}
</Text>
<MaterialCommunityIcons
name="star"
color={props.theme.colors.tetrisScore}
size={10}
style={{
marginTop: 'auto',
marginBottom: 'auto',
marginLeft: 5,
}}
/>
</View>
</View>
);
}
getControlButtons(): React.Node {
const {props} = this;
return (
<View
style={{
height: 80,
flexDirection: 'row',
}}>
<IconButton
icon="rotate-right-variant"
size={40}
onPress={() => {
this.logic.rotatePressed(this.updateGrid);
}}
style={{flex: 1}}
/>
<View
style={{
flexDirection: 'row',
flex: 4,
}}>
<IconButton
icon="chevron-left"
size={40}
style={{flex: 1}}
onPress={() => {
this.logic.pressedOut();
}}
onPressIn={() => {
this.logic.leftPressedIn(this.updateGrid);
}}
/>
<IconButton
icon="chevron-right"
size={40}
style={{flex: 1}}
onPress={() => {
this.logic.pressedOut();
}}
onPressIn={() => {
this.logic.rightPressed(this.updateGrid);
}}
/>
</View>
<IconButton
icon="arrow-down-bold"
size={40}
onPressIn={() => {
this.logic.downPressedIn(this.updateGridScore);
}}
onPress={() => {
this.logic.pressedOut();
}}
style={{flex: 1}}
color={props.theme.colors.tetrisScore}
/>
</View>
);
}
updateGrid = (newGrid: GridType) => {
this.setState({
grid: newGrid,
});
};
updateGridScore = (newGrid: GridType, score?: number) => {
this.setState((prevState: StateType): {
grid: GridType,
gameScore: number,
} => ({
grid: newGrid,
gameScore: score != null ? score : prevState.gameScore,
}));
};
togglePause = () => {
this.logic.togglePause();
if (this.logic.isGamePaused())
this.showPausePopup();
}
onDialogDismiss = () => this.setState({dialogVisible: false});
if (this.logic.isGamePaused()) this.showPausePopup();
};
showPausePopup = () => {
const onDismiss = () => {
@ -134,228 +354,56 @@ class GameMainScreen extends React.Component<Props, State> {
};
this.setState({
dialogVisible: true,
dialogTitle: i18n.t("screens.game.pause"),
dialogMessage: i18n.t("screens.game.pauseMessage"),
dialogTitle: i18n.t('screens.game.pause'),
dialogMessage: i18n.t('screens.game.pauseMessage'),
dialogButtons: [
{
title: i18n.t("screens.game.restart.text"),
onPress: this.showRestartConfirm
title: i18n.t('screens.game.restart.text'),
onPress: this.showRestartConfirm,
},
{
title: i18n.t("screens.game.resume"),
onPress: onDismiss
}
title: i18n.t('screens.game.resume'),
onPress: onDismiss,
},
],
onDialogDismiss: onDismiss,
});
}
};
showRestartConfirm = () => {
this.setState({
dialogVisible: true,
dialogTitle: i18n.t("screens.game.restart.confirm"),
dialogMessage: i18n.t("screens.game.restart.confirmMessage"),
dialogTitle: i18n.t('screens.game.restart.confirm'),
dialogMessage: i18n.t('screens.game.restart.confirmMessage'),
dialogButtons: [
{
title: i18n.t("screens.game.restart.confirmYes"),
title: i18n.t('screens.game.restart.confirmYes'),
onPress: () => {
this.onDialogDismiss();
this.startGame();
}
},
},
{
title: i18n.t("screens.game.restart.confirmNo"),
onPress: this.showPausePopup
}
title: i18n.t('screens.game.restart.confirmNo'),
onPress: this.showPausePopup,
},
],
onDialogDismiss: this.showPausePopup,
});
}
};
startGame = () => {
this.logic.startGame(this.onTick, this.onClock, this.onGameEnd);
this.setState({
gameRunning: true,
});
}
};
onGameEnd = (time: number, score: number, isRestart: boolean) => {
this.setState({
gameTime: time,
gameScore: score,
gameRunning: false,
});
if (!isRestart)
this.props.navigation.replace(
"game-start",
{
score: this.state.gameScore,
level: this.state.gameLevel,
time: this.state.gameTime,
}
);
}
getStatusIcons() {
return (
<View style={{
flex: 1,
marginTop: "auto",
marginBottom: "auto"
}}>
<View style={{
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Caption style={{
marginLeft: "auto",
marginRight: "auto",
marginBottom: 5,
}}>{i18n.t("screens.game.time")}</Caption>
<View style={{
flexDirection: "row"
}}>
<MaterialCommunityIcons
name={'timer'}
color={this.props.theme.colors.subtitle}
size={20}/>
<Text style={{
marginLeft: 5,
color: this.props.theme.colors.subtitle
}}>{this.getFormattedTime(this.state.gameTime)}</Text>
</View>
</View>
<View style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 20,
}}>
<Caption style={{
marginLeft: "auto",
marginRight: "auto",
marginBottom: 5,
}}>{i18n.t("screens.game.level")}</Caption>
<View style={{
flexDirection: "row"
}}>
<MaterialCommunityIcons
name={'gamepad-square'}
color={this.props.theme.colors.text}
size={20}/>
<Text style={{
marginLeft: 5
}}>{this.state.gameLevel}</Text>
</View>
</View>
</View>
);
}
getScoreIcon() {
let highScore = this.highScore == null || this.state.gameScore > this.highScore
? this.state.gameScore
: this.highScore;
return (
<View style={{
marginTop: 10,
marginBottom: 10,
}}>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
}}>
<Text style={{
marginLeft: 5,
fontSize: 20,
}}>{i18n.t("screens.game.score", {score: this.state.gameScore})}</Text>
<MaterialCommunityIcons
name={'star'}
color={this.props.theme.colors.tetrisScore}
size={20}
style={{
marginTop: "auto",
marginBottom: "auto",
marginLeft: 5
}}/>
</View>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
marginTop: 5,
}}>
<Text style={{
marginLeft: 5,
fontSize: 10,
color: this.props.theme.colors.textDisabled
}}>{i18n.t("screens.game.highScore", {score: highScore})}</Text>
<MaterialCommunityIcons
name={'star'}
color={this.props.theme.colors.tetrisScore}
size={10}
style={{
marginTop: "auto",
marginBottom: "auto",
marginLeft: 5
}}/>
</View>
</View>
);
}
getControlButtons() {
return (
<View style={{
height: 80,
flexDirection: "row"
}}>
<IconButton
icon="rotate-right-variant"
size={40}
onPress={() => this.logic.rotatePressed(this.updateGrid)}
style={{flex: 1}}
/>
<View style={{
flexDirection: 'row',
flex: 4
}}>
<IconButton
icon="chevron-left"
size={40}
style={{flex: 1}}
onPress={() => this.logic.pressedOut()}
onPressIn={() => this.logic.leftPressedIn(this.updateGrid)}
/>
<IconButton
icon="chevron-right"
size={40}
style={{flex: 1}}
onPress={() => this.logic.pressedOut()}
onPressIn={() => this.logic.rightPressed(this.updateGrid)}
/>
</View>
<IconButton
icon="arrow-down-bold"
size={40}
onPressIn={() => this.logic.downPressedIn(this.updateGridScore)}
onPress={() => this.logic.pressedOut()}
style={{flex: 1}}
color={this.props.theme.colors.tetrisScore}
/>
</View>
);
}
render() {
render(): React.Node {
const {props, state} = this;
return (
<View style={{flex: 1}}>
<View style={{
<View
style={{
flex: 1,
flexDirection: "row",
flexDirection: 'row',
}}>
{this.getStatusIcons()}
<View style={{flex: 4}}>
@ -363,12 +411,12 @@ class GameMainScreen extends React.Component<Props, State> {
<GridComponent
width={this.logic.getWidth()}
height={this.logic.getHeight()}
grid={this.state.grid}
grid={state.grid}
style={{
backgroundColor: this.props.theme.colors.tetrisBackground,
backgroundColor: props.theme.colors.tetrisBackground,
flex: 1,
marginLeft: "auto",
marginRight: "auto",
marginLeft: 'auto',
marginRight: 'auto',
}}
/>
</View>
@ -387,16 +435,15 @@ class GameMainScreen extends React.Component<Props, State> {
{this.getControlButtons()}
<OptionsDialog
visible={this.state.dialogVisible}
title={this.state.dialogTitle}
message={this.state.dialogMessage}
buttons={this.state.dialogButtons}
onDismiss={this.state.onDialogDismiss}
visible={state.dialogVisible}
title={state.dialogTitle}
message={state.dialogMessage}
buttons={state.dialogButtons}
onDismiss={state.onDialogDismiss}
/>
</View>
);
}
}
export default withTheme(GameMainScreen);

View file

@ -1,111 +1,105 @@
// @flow
import * as React from "react";
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../../managers/ThemeManager";
import {Button, Card, Divider, Headline, Paragraph, Text, withTheme} from "react-native-paper";
import {View} from "react-native";
import i18n from "i18n-js";
import Mascot, {MASCOT_STYLE} from "../../../components/Mascot/Mascot";
import MascotPopup from "../../../components/Mascot/MascotPopup";
import AsyncStorageManager from "../../../managers/AsyncStorageManager";
import type {Grid} from "../components/GridComponent";
import GridComponent from "../components/GridComponent";
import GridManager from "../logic/GridManager";
import Piece from "../logic/Piece";
import * as Animatable from "react-native-animatable";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import LinearGradient from "react-native-linear-gradient";
import SpeechArrow from "../../../components/Mascot/SpeechArrow";
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
import * as React from 'react';
import {StackNavigationProp} from '@react-navigation/stack';
import {
Button,
Card,
Divider,
Headline,
Paragraph,
Text,
withTheme,
} from 'react-native-paper';
import {View} from 'react-native';
import i18n from 'i18n-js';
import * as Animatable from 'react-native-animatable';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import LinearGradient from 'react-native-linear-gradient';
import type {CustomThemeType} from '../../../managers/ThemeManager';
import Mascot, {MASCOT_STYLE} from '../../../components/Mascot/Mascot';
import MascotPopup from '../../../components/Mascot/MascotPopup';
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import type {GridType} from '../components/GridComponent';
import GridComponent from '../components/GridComponent';
import GridManager from '../logic/GridManager';
import Piece from '../logic/Piece';
import SpeechArrow from '../../../components/Mascot/SpeechArrow';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
type GameStats = {
type GameStatsType = {
score: number,
level: number,
time: number,
}
};
type Props = {
type PropsType = {
navigation: StackNavigationProp,
route: {
params: GameStats
params: GameStatsType,
},
theme: CustomTheme,
}
class GameStartScreen extends React.Component<Props> {
theme: CustomThemeType,
};
class GameStartScreen extends React.Component<PropsType> {
gridManager: GridManager;
scores: Array<number>;
gameStats: GameStats | null;
gameStats: GameStatsType | null;
isHighScore: boolean;
constructor(props: Props) {
constructor(props: PropsType) {
super(props);
this.gridManager = new GridManager(4, 4, props.theme);
this.scores = AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.gameScores.key);
this.scores.sort((a, b) => b - a);
if (this.props.route.params != null)
this.recoverGameScore();
this.scores = AsyncStorageManager.getObject(
AsyncStorageManager.PREFERENCES.gameScores.key,
);
this.scores.sort((a: number, b: number): number => b - a);
if (props.route.params != null) this.recoverGameScore();
}
recoverGameScore() {
this.gameStats = this.props.route.params;
this.isHighScore = this.scores.length === 0 || this.gameStats.score > this.scores[0];
for (let i = 0; i < 3; i++) {
if (this.scores.length > i && this.gameStats.score > this.scores[i]) {
this.scores.splice(i, 0, this.gameStats.score);
break;
} else if (this.scores.length <= i) {
this.scores.push(this.gameStats.score);
break;
}
}
if (this.scores.length > 3)
this.scores.splice(3, 1);
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.gameScores.key, this.scores);
}
getPiecesBackground() {
let gridList = [];
for (let i = 0; i < 18; i++) {
getPiecesBackground(): React.Node {
const {theme} = this.props;
const gridList = [];
for (let i = 0; i < 18; i += 1) {
gridList.push(this.gridManager.getEmptyGrid(4, 4));
const piece = new Piece(this.props.theme);
const piece = new Piece(theme);
piece.toGrid(gridList[i], true);
}
return (
<View style={{
position: "absolute",
width: "100%",
height: "100%",
<View
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}>
{gridList.map((item: Grid, index: number) => {
{gridList.map((item: GridType, index: number): React.Node => {
const size = 10 + Math.floor(Math.random() * 30);
const top = Math.floor(Math.random() * 100);
const rot = Math.floor(Math.random() * 360);
const left = (index % 6) * 20;
const animDelay = size * 20;
const animDuration = 2 * (2000 - (size * 30));
const animDuration = 2 * (2000 - size * 30);
return (
<Animatable.View
animation={"fadeInDownBig"}
animation="fadeInDownBig"
delay={animDelay}
duration={animDuration}
key={"piece" + index.toString()}
key={`piece${index.toString()}`}
style={{
width: size + "%",
position: "absolute",
top: top + "%",
left: left + "%",
}}
>
width: `${size}%`,
position: 'absolute',
top: `${top}%`,
left: `${left}%`,
}}>
<GridComponent
width={4}
height={4}
grid={item}
style={{
transform: [{rotateZ: rot + "deg"}],
transform: [{rotateZ: `${rot}deg`}],
}}
/>
</Animatable.View>
@ -115,26 +109,30 @@ class GameStartScreen extends React.Component<Props> {
);
}
getPostGameContent(stats: GameStats) {
getPostGameContent(stats: GameStatsType): React.Node {
const {props} = this;
return (
<View style={{
flex: 1
<View
style={{
flex: 1,
}}>
<Mascot
emotion={this.isHighScore ? MASCOT_STYLE.LOVE : MASCOT_STYLE.NORMAL}
animated={this.isHighScore}
style={{
width: this.isHighScore ? "50%" : "30%",
marginLeft: this.isHighScore ? "auto" : null,
marginRight: this.isHighScore ? "auto" : null,
}}/>
<SpeechArrow
style={{marginLeft: this.isHighScore ? "60%" : "20%"}}
size={20}
color={this.props.theme.colors.mascotMessageArrow}
width: this.isHighScore ? '50%' : '30%',
marginLeft: this.isHighScore ? 'auto' : null,
marginRight: this.isHighScore ? 'auto' : null,
}}
/>
<Card style={{
borderColor: this.props.theme.colors.mascotMessageArrow,
<SpeechArrow
style={{marginLeft: this.isHighScore ? '60%' : '20%'}}
size={20}
color={props.theme.colors.mascotMessageArrow}
/>
<Card
style={{
borderColor: props.theme.colors.mascotMessageArrow,
borderWidth: 2,
marginLeft: 20,
marginRight: 20,
@ -142,95 +140,101 @@ class GameStartScreen extends React.Component<Props> {
<Card.Content>
<Headline
style={{
textAlign: "center",
textAlign: 'center',
color: this.isHighScore
? this.props.theme.colors.gameGold
: this.props.theme.colors.primary
? props.theme.colors.gameGold
: props.theme.colors.primary,
}}>
{this.isHighScore
? i18n.t("screens.game.newHighScore")
: i18n.t("screens.game.gameOver")}
? i18n.t('screens.game.newHighScore')
: i18n.t('screens.game.gameOver')}
</Headline>
<Divider/>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
<Divider />
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
marginBottom: 10,
}}>
<Text style={{
<Text
style={{
fontSize: 20,
}}>
{i18n.t("screens.game.score", {score: stats.score})}
{i18n.t('screens.game.score', {score: stats.score})}
</Text>
<MaterialCommunityIcons
name={'star'}
color={this.props.theme.colors.tetrisScore}
name="star"
color={props.theme.colors.tetrisScore}
size={30}
style={{
marginLeft: 5
}}/>
marginLeft: 5,
}}
/>
</View>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Text>{i18n.t("screens.game.level")}</Text>
<Text>{i18n.t('screens.game.level')}</Text>
<MaterialCommunityIcons
style={{
marginRight: 5,
marginLeft: 5,
}}
name={"gamepad-square"}
name="gamepad-square"
size={20}
color={this.props.theme.colors.textDisabled}
color={props.theme.colors.textDisabled}
/>
<Text>
{stats.level}
</Text>
<Text>{stats.level}</Text>
</View>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Text>{i18n.t("screens.game.time")}</Text>
<Text>{i18n.t('screens.game.time')}</Text>
<MaterialCommunityIcons
style={{
marginRight: 5,
marginLeft: 5,
}}
name={"timer"}
name="timer"
size={20}
color={this.props.theme.colors.textDisabled}
color={props.theme.colors.textDisabled}
/>
<Text>
{stats.time}
</Text>
<Text>{stats.time}</Text>
</View>
</Card.Content>
</Card>
</View>
)
);
}
getWelcomeText() {
getWelcomeText(): React.Node {
const {props} = this;
return (
<View>
<Mascot emotion={MASCOT_STYLE.COOL} style={{
width: "40%",
marginLeft: "auto",
marginRight: "auto",
}}/>
<SpeechArrow
style={{marginLeft: "60%"}}
size={20}
color={this.props.theme.colors.mascotMessageArrow}
<Mascot
emotion={MASCOT_STYLE.COOL}
style={{
width: '40%',
marginLeft: 'auto',
marginRight: 'auto',
}}
/>
<Card style={{
borderColor: this.props.theme.colors.mascotMessageArrow,
<SpeechArrow
style={{marginLeft: '60%'}}
size={20}
color={props.theme.colors.mascotMessageArrow}
/>
<Card
style={{
borderColor: props.theme.colors.mascotMessageArrow,
borderWidth: 2,
marginLeft: 10,
marginRight: 10,
@ -238,18 +242,18 @@ class GameStartScreen extends React.Component<Props> {
<Card.Content>
<Headline
style={{
textAlign: "center",
color: this.props.theme.colors.primary
textAlign: 'center',
color: props.theme.colors.primary,
}}>
{i18n.t("screens.game.welcomeTitle")}
{i18n.t('screens.game.welcomeTitle')}
</Headline>
<Divider/>
<Divider />
<Paragraph
style={{
textAlign: "center",
textAlign: 'center',
marginTop: 10,
}}>
{i18n.t("screens.game.welcomeMessage")}
{i18n.t('screens.game.welcomeMessage')}
</Paragraph>
</Card.Content>
</Card>
@ -257,93 +261,88 @@ class GameStartScreen extends React.Component<Props> {
);
}
getPodiumRender(place: 1 | 2 | 3, score: string) {
let icon = "podium-gold";
let color = this.props.theme.colors.gameGold;
getPodiumRender(place: 1 | 2 | 3, score: string): React.Node {
const {props} = this;
let icon = 'podium-gold';
let color = props.theme.colors.gameGold;
let fontSize = 20;
let size = 70;
if (place === 2) {
icon = "podium-silver";
color = this.props.theme.colors.gameSilver;
icon = 'podium-silver';
color = props.theme.colors.gameSilver;
fontSize = 18;
size = 60;
} else if (place === 3) {
icon = "podium-bronze";
color = this.props.theme.colors.gameBronze;
icon = 'podium-bronze';
color = props.theme.colors.gameBronze;
fontSize = 15;
size = 50;
}
return (
<View style={{
marginLeft: place === 2 ? 20 : "auto",
marginRight: place === 3 ? 20 : "auto",
flexDirection: "column",
alignItems: "center",
justifyContent: "flex-end",
<View
style={{
marginLeft: place === 2 ? 20 : 'auto',
marginRight: place === 3 ? 20 : 'auto',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'flex-end',
}}>
{
this.isHighScore && place === 1
?
{this.isHighScore && place === 1 ? (
<Animatable.View
animation={"swing"}
iterationCount={"infinite"}
animation="swing"
iterationCount="infinite"
duration={2000}
delay={1000}
useNativeDriver={true}
useNativeDriver
style={{
position: "absolute",
top: -20
}}
>
position: 'absolute',
top: -20,
}}>
<Animatable.View
animation={"pulse"}
iterationCount={"infinite"}
useNativeDriver={true}
>
animation="pulse"
iterationCount="infinite"
useNativeDriver>
<MaterialCommunityIcons
name={"decagram"}
color={this.props.theme.colors.gameGold}
name="decagram"
color={props.theme.colors.gameGold}
size={150}
/>
</Animatable.View>
</Animatable.View>
: null
}
) : null}
<MaterialCommunityIcons
name={icon}
color={this.isHighScore && place === 1 ? "#fff" : color}
color={this.isHighScore && place === 1 ? '#fff' : color}
size={size}
/>
<Text style={{
textAlign: "center",
fontWeight: place === 1 ? "bold" : null,
fontSize: fontSize,
}}>{score}</Text>
<Text
style={{
textAlign: 'center',
fontWeight: place === 1 ? 'bold' : null,
fontSize,
}}>
{score}
</Text>
</View>
);
}
getTopScoresRender() {
const gold = this.scores.length > 0
? this.scores[0]
: "-";
const silver = this.scores.length > 1
? this.scores[1]
: "-";
const bronze = this.scores.length > 2
? this.scores[2]
: "-";
getTopScoresRender(): React.Node {
const gold = this.scores.length > 0 ? this.scores[0] : '-';
const silver = this.scores.length > 1 ? this.scores[1] : '-';
const bronze = this.scores.length > 2 ? this.scores[2] : '-';
return (
<View style={{
<View
style={{
marginBottom: 20,
marginTop: 20
marginTop: 20,
}}>
{this.getPodiumRender(1, gold.toString())}
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
}}>
{this.getPodiumRender(3, bronze.toString())}
{this.getPodiumRender(2, silver.toString())}
@ -352,76 +351,90 @@ class GameStartScreen extends React.Component<Props> {
);
}
getMainContent() {
getMainContent(): React.Node {
const {props} = this;
return (
<View style={{flex: 1}}>
{
this.gameStats != null
{this.gameStats != null
? this.getPostGameContent(this.gameStats)
: this.getWelcomeText()
}
: this.getWelcomeText()}
<Button
icon={"play"}
mode={"contained"}
onPress={() => this.props.navigation.replace(
"game-main",
{
highScore: this.scores.length > 0
? this.scores[0]
: null
}
)}
style={{
marginLeft: "auto",
marginRight: "auto",
marginTop: 10,
icon="play"
mode="contained"
onPress={() => {
props.navigation.replace('game-main', {
highScore: this.scores.length > 0 ? this.scores[0] : null,
});
}}
>
{i18n.t("screens.game.play")}
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
}}>
{i18n.t('screens.game.play')}
</Button>
{this.getTopScoresRender()}
</View>
)
);
}
keyExtractor = (item: number) => item.toString();
keyExtractor = (item: number): string => item.toString();
render() {
recoverGameScore() {
const {route} = this.props;
this.gameStats = route.params;
this.isHighScore =
this.scores.length === 0 || this.gameStats.score > this.scores[0];
for (let i = 0; i < 3; i += 1) {
if (this.scores.length > i && this.gameStats.score > this.scores[i]) {
this.scores.splice(i, 0, this.gameStats.score);
break;
} else if (this.scores.length <= i) {
this.scores.push(this.gameStats.score);
break;
}
}
if (this.scores.length > 3) this.scores.splice(3, 1);
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.gameScores.key,
this.scores,
);
}
render(): React.Node {
const {props} = this;
return (
<View style={{flex: 1}}>
{this.getPiecesBackground()}
<LinearGradient
style={{flex: 1}}
colors={[
this.props.theme.colors.background + "00",
this.props.theme.colors.background
`${props.theme.colors.background}00`,
props.theme.colors.background,
]}
start={{x: 0, y: 0}}
end={{x: 0, y: 1}}
>
end={{x: 0, y: 1}}>
<CollapsibleScrollView>
{this.getMainContent()}
<MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.gameStartShowBanner.key}
title={i18n.t("screens.game.mascotDialog.title")}
message={i18n.t("screens.game.mascotDialog.message")}
icon={"gamepad-variant"}
title={i18n.t('screens.game.mascotDialog.title')}
message={i18n.t('screens.game.mascotDialog.message')}
icon="gamepad-variant"
buttons={{
action: null,
cancel: {
message: i18n.t("screens.game.mascotDialog.button"),
icon: "check",
}
message: i18n.t('screens.game.mascotDialog.button'),
icon: 'check',
},
}}
emotion={MASCOT_STYLE.COOL}
/>
</CollapsibleScrollView>
</LinearGradient>
</View>
);
}
}
export default withTheme(GameStartScreen);