refactor: Формат хранения кирпичей в классе Game переписан с вложенного массива на обычный массив. Входные данные для значений каждого кирпича берутся из карты уровней
This commit is contained in:
@@ -1,37 +1,35 @@
|
|||||||
import { Brick } from '../brick';
|
import { Brick } from '../brick';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ложит кирпичи по заданым размерам
|
* Создает массив кирпичей проинициализированных значениями в зависимости от расположения на карте уровня
|
||||||
* @param {number} columnAmount количество кирпичей по оси X, неотрицателное, целое число
|
* @param {number[][]} levelMap карта уровня в формате массива
|
||||||
* @param {number} rowAmount количество кирпичей по оси Y, неотрицателное, целое число
|
|
||||||
* @param {number} brickWidth ширина кирпича, неотрицателное число
|
* @param {number} brickWidth ширина кирпича, неотрицателное число
|
||||||
* @param {number} brickHeight длина кирпича, неотрицателное число
|
* @param {number} brickHeight длина кирпича, неотрицателное число
|
||||||
* @returns {Brick[][]} массив с массивами кирпичей
|
* @returns {Brick[]} массив кирпичей
|
||||||
*/
|
*/
|
||||||
export function layBricks(columnAmount, rowAmount, brickWidth, brickHeight) {
|
export function layBricks(levelMap, brickWidth, brickHeight) {
|
||||||
try {
|
try {
|
||||||
const someArgsArentNumbers = [columnAmount, rowAmount, brickWidth, brickHeight].some(
|
if (!(Array.isArray(levelMap) && levelMap.every(Array.isArray))) {
|
||||||
(arg) => typeof arg !== 'number',
|
throw new Error('Значение карты уровня должно являться вложенным масивом чисел глубины 2');
|
||||||
);
|
|
||||||
if (someArgsArentNumbers) {
|
|
||||||
throw new Error('Параметры кладки кирпичей должны являться числами');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const someArgsLessThanZero = [columnAmount, rowAmount, brickWidth, brickHeight].some((arg) => arg < 0);
|
if (!(typeof brickWidth === 'number' && typeof brickHeight === 'number')) {
|
||||||
if (someArgsLessThanZero) {
|
throw new Error('Значения ширины и высоты кирпича должны являться числами');
|
||||||
throw new Error('Параметры кладки кирпичей должны являться положительными целыми числами');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rowsOrColumnsAreFloat = [columnAmount, rowAmount].some((amount) => amount % 1 !== 0);
|
if (brickWidth < 0 || brickHeight < 0) {
|
||||||
if (rowsOrColumnsAreFloat) {
|
throw new Error('Значения ширины и высоты кирпича должны являться положительными целыми числами');
|
||||||
throw new Error('Размеры рядов и колонок должны являться целыми числами');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const bricks = Array.from({ length: rowAmount }).map((_, rowIndex) =>
|
const bricks = [];
|
||||||
Array.from({ length: columnAmount }).map(
|
|
||||||
(_, columnIndex) => new Brick(columnIndex * brickWidth, rowIndex * brickHeight, brickWidth, brickHeight),
|
for (let i = 0; i < levelMap.length; i++) {
|
||||||
),
|
for (let j = 0; j < levelMap[i].length; j++) {
|
||||||
);
|
if (levelMap[i][j] !== 0) {
|
||||||
|
bricks.push(new Brick(j * brickWidth, i * brickHeight, brickWidth, brickHeight));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return bricks;
|
return bricks;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -5,54 +5,63 @@ describe('layBricks', () => {
|
|||||||
it('Возвращает корректное значение в случае неверного типа параметра', () => {
|
it('Возвращает корректное значение в случае неверного типа параметра', () => {
|
||||||
const wrongType = 'wrong';
|
const wrongType = 'wrong';
|
||||||
|
|
||||||
expect(layBricks(wrongType, 1, 1, 1)).toBeNull();
|
expect(layBricks(wrongType, 1, 1)).toBeNull();
|
||||||
expect(layBricks(1, wrongType, 1, 1)).toBeNull();
|
expect(layBricks(1, wrongType, 1)).toBeNull();
|
||||||
expect(layBricks(1, 1, wrongType, 1)).toBeNull();
|
expect(layBricks(1, 1, wrongType)).toBeNull();
|
||||||
expect(layBricks(1, 1, 1, wrongType)).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Возвращает корректное значение в случае неверных размеров кирпича', () => {
|
it('Возвращает корректное значение в случае неверных размеров кирпича', () => {
|
||||||
const wrongWidth = -1;
|
const wrongWidth = -1;
|
||||||
const wrongHeight = -1;
|
const wrongHeight = -1;
|
||||||
|
|
||||||
expect(layBricks(1, 1, wrongWidth, 1)).toBeNull();
|
expect(layBricks(1, wrongWidth, 1)).toBeNull();
|
||||||
expect(layBricks(1, 1, 1, wrongHeight)).toBeNull();
|
expect(layBricks(1, 1, wrongHeight)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Возвращает корректное значение в случае неверных значений рядов и колонок', () => {
|
it('Возвращает корректное значение в случае некоректной карты уровня', () => {
|
||||||
const negativeRow = -1;
|
const levelMap = ['brick', 'brick'];
|
||||||
const negativeColumn = -1;
|
|
||||||
const decimalRow = 1.5;
|
|
||||||
const decimalColumn = 1.5;
|
|
||||||
|
|
||||||
expect(layBricks(negativeRow, 1, 1, 1)).toBeNull();
|
expect(layBricks(levelMap, 1, 1)).toBeNull();
|
||||||
expect(layBricks(1, negativeColumn, 1, 1)).toBeNull();
|
|
||||||
expect(layBricks(decimalRow, 1, 1, 1)).toBeNull();
|
|
||||||
expect(layBricks(1, decimalColumn, 1, 1)).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Возвращает массив корректных размеров', () => {
|
it('Возвращает массив корректных размеров', () => {
|
||||||
const columnAmount = 10;
|
const levelMap = [
|
||||||
const rowAmount = 5;
|
[1, 1, 1, 1, 1],
|
||||||
|
[1, 1, 1, 1, 1],
|
||||||
|
[1, 1, 1, 1, 1],
|
||||||
|
];
|
||||||
|
|
||||||
const bricks = layBricks(columnAmount, rowAmount, 1, 1);
|
const bricks = layBricks(levelMap, 1, 1);
|
||||||
expect(bricks.length).toEqual(rowAmount);
|
expect(bricks.length).toBe(levelMap.flat().length);
|
||||||
for (const row of bricks) {
|
|
||||||
expect(row.length).toEqual(columnAmount);
|
const emptyLevelMap = [
|
||||||
}
|
[0, 0, 0, 0, 0],
|
||||||
|
[0, 0, 0, 0, 0],
|
||||||
|
[0, 0, 0, 0, 0],
|
||||||
|
];
|
||||||
|
const emptyBricksArray = layBricks(emptyLevelMap, 1, 1);
|
||||||
|
expect(emptyBricksArray.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Задает корректные координаты кирпичам', () => {
|
it('Задает корректные координаты кирпичам', () => {
|
||||||
const bricks = layBricks(3, 3, 1, 1);
|
const levelMap = [
|
||||||
const columnAmount = 10;
|
[1, 1],
|
||||||
const rowAmount = 5;
|
[1, 1],
|
||||||
|
];
|
||||||
|
const brickWidth = 1;
|
||||||
|
const brickHeight = 1;
|
||||||
|
|
||||||
const brickss = layBricks(columnAmount, rowAmount, 1, 1);
|
const bricks = layBricks(levelMap, brickWidth, brickHeight);
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
for (let i = 0; i < rowAmount; i++) {
|
for (let i = 0; i < levelMap.length; i++) {
|
||||||
for (let j = 0; j < columnAmount; j++) {
|
for (let j = 0; j < levelMap[i].length; j++) {
|
||||||
expect(brickss[i][j].x).toEqual(j);
|
if (levelMap[i][j] === 0) {
|
||||||
expect(brickss[i][j]?.y).toEqual(i);
|
continue;
|
||||||
|
}
|
||||||
|
expect(bricks[index].x).toBe(j * brickWidth);
|
||||||
|
expect(bricks[index].y).toBe(i * brickHeight);
|
||||||
|
index++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+6
-6
@@ -20,12 +20,13 @@ import { toRadians } from './lib/toRadians/toRadians';
|
|||||||
*/
|
*/
|
||||||
export class Game {
|
export class Game {
|
||||||
/**
|
/**
|
||||||
* @param {number} columnAmount количество кирпичей по оси X, неотрицателное, целое число
|
* @param {number[][][]} levels список уровней, каждый элемент которого - карта расположения блоков
|
||||||
* @param {number} rowAmount количество кирпичей по оси Y, неотрицателное, целое число
|
|
||||||
*/
|
*/
|
||||||
constructor(columnAmount, rowAmount) {
|
constructor(levels) {
|
||||||
this.livesAmount = 3;
|
this.livesAmount = 3;
|
||||||
this.status = 'in_process';
|
this.status = 'in_process';
|
||||||
|
this.currentLevel = 0;
|
||||||
|
this.maxLevel = levels.length - 1;
|
||||||
|
|
||||||
this.ball = new Ball(
|
this.ball = new Ball(
|
||||||
CONTAINER_WIDTH / 2 - BALL_RADIUS / 2,
|
CONTAINER_WIDTH / 2 - BALL_RADIUS / 2,
|
||||||
@@ -35,8 +36,7 @@ export class Game {
|
|||||||
-1 * BALL_SPEED * Math.sin(toRadians(BALL_INITIAL_ANGLE)),
|
-1 * BALL_SPEED * Math.sin(toRadians(BALL_INITIAL_ANGLE)),
|
||||||
);
|
);
|
||||||
this.paddle = new Paddle(0, CONTAINER_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT);
|
this.paddle = new Paddle(0, CONTAINER_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT);
|
||||||
|
this.bricks = layBricks(levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT);
|
||||||
this.bricks = layBricks(columnAmount, rowAmount, BRICK_WIDTH, BRICK_HEIGHT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,7 +59,7 @@ export class Game {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAnyBrickAlive = this.bricks.some((row) => row.some((brick) => brick.alive));
|
const isAnyBrickAlive = this.bricks.some((brick) => brick.alive);
|
||||||
|
|
||||||
if (!isAnyBrickAlive) {
|
if (!isAnyBrickAlive) {
|
||||||
this.status = 'completed';
|
this.status = 'completed';
|
||||||
|
|||||||
+22
-24
@@ -66,36 +66,34 @@ export function tick(game, containerWidth, containerHeight, deltaTime) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Базоввое взаимодействие мяча и кирпича
|
// Базоввое взаимодействие мяча и кирпича
|
||||||
for (const row of bricks) {
|
for (const brick of bricks) {
|
||||||
for (const brick of row) {
|
if (!brick.alive) {
|
||||||
if (!brick.alive) {
|
continue;
|
||||||
continue;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const ballLeft = ball.x - ball.radius;
|
const ballLeft = ball.x - ball.radius;
|
||||||
const ballRight = ball.x + ball.radius;
|
const ballRight = ball.x + ball.radius;
|
||||||
const ballTop = ball.y - ball.radius;
|
const ballTop = ball.y - ball.radius;
|
||||||
const ballBottom = ball.y + ball.radius;
|
const ballBottom = ball.y + ball.radius;
|
||||||
|
|
||||||
const brickLeft = brick.x;
|
const brickLeft = brick.x;
|
||||||
const brickRight = brick.x + brick.width;
|
const brickRight = brick.x + brick.width;
|
||||||
const brickTop = brick.y;
|
const brickTop = brick.y;
|
||||||
const brickBottom = brick.y + brick.height;
|
const brickBottom = brick.y + brick.height;
|
||||||
|
|
||||||
const ballObject = { left: ballLeft, right: ballRight, top: ballTop, bottom: ballBottom };
|
const ballObject = { left: ballLeft, right: ballRight, top: ballTop, bottom: ballBottom };
|
||||||
const brickObject = { left: brickLeft, right: brickRight, top: brickTop, bottom: brickBottom };
|
const brickObject = { left: brickLeft, right: brickRight, top: brickTop, bottom: brickBottom };
|
||||||
|
|
||||||
const isCollided = calculateCollision(ballObject, brickObject);
|
const isCollided = calculateCollision(ballObject, brickObject);
|
||||||
|
|
||||||
if (isCollided) {
|
if (isCollided) {
|
||||||
const directions = calculateDirection(ballObject, brickObject);
|
const directions = calculateDirection(ballObject, brickObject);
|
||||||
|
|
||||||
if (directions !== null) {
|
if (directions !== null) {
|
||||||
ball.horizontalSpeed *= directions[0];
|
ball.horizontalSpeed *= directions[0];
|
||||||
ball.verticalSpeed *= directions[1];
|
ball.verticalSpeed *= directions[1];
|
||||||
brick.kill();
|
brick.kill();
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Возвращает корректное значние и не изменяет свойства game при неверых размерах контейнера', () => {
|
it('Возвращает корректное значние и не изменяет свойства game при неверых размерах контейнера', () => {
|
||||||
const game = new Game(1, 1);
|
const levels = [[[1]]];
|
||||||
|
const game = new Game(levels);
|
||||||
const ballX = game.ball.x;
|
const ballX = game.ball.x;
|
||||||
const ballY = game.ball.y;
|
const ballY = game.ball.y;
|
||||||
expect(tick(game, -1, -1, 1)).toBeNull();
|
expect(tick(game, -1, -1, 1)).toBeNull();
|
||||||
@@ -20,7 +21,8 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Возвращает корректное значние и не изменяет свойства game при неверном значении времени', () => {
|
it('Возвращает корректное значние и не изменяет свойства game при неверном значении времени', () => {
|
||||||
const game = new Game(1, 1);
|
const levels = [[[1]]];
|
||||||
|
const game = new Game(levels);
|
||||||
const ballX = game.ball.x;
|
const ballX = game.ball.x;
|
||||||
const ballY = game.ball.y;
|
const ballY = game.ball.y;
|
||||||
expect(tick(game, 1, 1, -1)).toBeNull();
|
expect(tick(game, 1, 1, -1)).toBeNull();
|
||||||
@@ -29,7 +31,8 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Меняет направление мяча при столкновении со стеной', () => {
|
it('Меняет направление мяча при столкновении со стеной', () => {
|
||||||
const game = new Game(1, 1);
|
const levels = [[[1]]];
|
||||||
|
const game = new Game(levels);
|
||||||
game.ball.x = 0;
|
game.ball.x = 0;
|
||||||
game.ball.horizontalSpeed = -10;
|
game.ball.horizontalSpeed = -10;
|
||||||
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1);
|
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1);
|
||||||
@@ -38,7 +41,8 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Меняет направление мяча при столкновении с потолком', () => {
|
it('Меняет направление мяча при столкновении с потолком', () => {
|
||||||
const game = new Game(0, 0);
|
const levels = [[[1]]];
|
||||||
|
const game = new Game(1);
|
||||||
game.ball.y = 0;
|
game.ball.y = 0;
|
||||||
game.ball.verticalSpeed = -10;
|
game.ball.verticalSpeed = -10;
|
||||||
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1);
|
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1);
|
||||||
@@ -47,8 +51,9 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Убивает кирпич при столкновении и отражает мяч', () => {
|
it('Убивает кирпич при столкновении и отражает мяч', () => {
|
||||||
const game = new Game(1, 1);
|
const levels = [[[1]]];
|
||||||
const brick = game.bricks[0][0];
|
const game = new Game(levels);
|
||||||
|
const brick = game.bricks[0];
|
||||||
|
|
||||||
game.ball.x = brick.x + game.ball.radius + 1;
|
game.ball.x = brick.x + game.ball.radius + 1;
|
||||||
game.ball.y = brick.y + brick.height + game.ball.radius + 1;
|
game.ball.y = brick.y + brick.height + game.ball.radius + 1;
|
||||||
@@ -62,8 +67,9 @@ describe('tick', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Убивает только один кирпич за тик', () => {
|
it('Убивает только один кирпич за тик', () => {
|
||||||
const game = new Game(2, 1);
|
const levels = [[[1, 1]]];
|
||||||
const [firstBrick, secondBrick] = game.bricks[0];
|
const game = new Game(levels);
|
||||||
|
const [firstBrick, secondBrick] = game.bricks;
|
||||||
|
|
||||||
game.ball.x = firstBrick.x + game.ball.radius + 1;
|
game.ball.x = firstBrick.x + game.ball.radius + 1;
|
||||||
game.ball.y = firstBrick.y + firstBrick.height + game.ball.radius + 1;
|
game.ball.y = firstBrick.y + firstBrick.height + game.ball.radius + 1;
|
||||||
@@ -72,7 +78,7 @@ describe('tick', () => {
|
|||||||
|
|
||||||
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 0.1);
|
tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 0.1);
|
||||||
|
|
||||||
const killedCount = game.bricks[0].filter((b) => !b.alive).length;
|
const killedCount = game.bricks.filter((b) => !b.alive).length;
|
||||||
expect(killedCount).toBe(1);
|
expect(killedCount).toBe(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+2
-1
@@ -13,6 +13,7 @@ import {
|
|||||||
PADDLE_HEIGHT,
|
PADDLE_HEIGHT,
|
||||||
PADDLE_WIDTH,
|
PADDLE_WIDTH,
|
||||||
} from './config';
|
} from './config';
|
||||||
|
import { LEVELS } from './const/levels';
|
||||||
import { Game } from './game';
|
import { Game } from './game';
|
||||||
import { calculateCollision } from './lib/calculateCollision/calculateCollision';
|
import { calculateCollision } from './lib/calculateCollision/calculateCollision';
|
||||||
import { calculateDirection } from './lib/calculateDirection/calculateDirection';
|
import { calculateDirection } from './lib/calculateDirection/calculateDirection';
|
||||||
@@ -39,7 +40,7 @@ import { createGameView, syncronizeViewsWithGame } from './view';
|
|||||||
|
|
||||||
app.stage.addChild(container);
|
app.stage.addChild(container);
|
||||||
|
|
||||||
const game = new Game(BRICK_COLUMN_AMOUNT, BRICK_ROW_AMOUNT);
|
const game = new Game(LEVELS);
|
||||||
const views = createGameView(game, container);
|
const views = createGameView(game, container);
|
||||||
|
|
||||||
container.on('pointermove', (event) => {
|
container.on('pointermove', (event) => {
|
||||||
|
|||||||
+10
-14
@@ -41,13 +41,11 @@ export function createGameView(game, container) {
|
|||||||
const paddle = createPaddleView(game.paddle);
|
const paddle = createPaddleView(game.paddle);
|
||||||
container.addChild(paddle);
|
container.addChild(paddle);
|
||||||
|
|
||||||
const bricks = game.bricks.map((row) =>
|
const bricks = game.bricks.map((brick) => {
|
||||||
row.map((brick) => {
|
const brickView = createBrickView(brick);
|
||||||
const brickView = createBrickView(brick);
|
container.addChild(brickView);
|
||||||
container.addChild(brickView);
|
return brickView;
|
||||||
return brickView;
|
});
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ball,
|
ball,
|
||||||
@@ -78,13 +76,11 @@ export function syncronizeViewsWithGame(views, game) {
|
|||||||
views.paddle.y = game.paddle.y;
|
views.paddle.y = game.paddle.y;
|
||||||
|
|
||||||
for (let i = 0; i < game.bricks.length; i++) {
|
for (let i = 0; i < game.bricks.length; i++) {
|
||||||
for (let j = 0; j < game.bricks[i].length; j++) {
|
const brick = game.bricks[i];
|
||||||
const brick = game.bricks[i][j];
|
const brickView = views.bricks[i];
|
||||||
const brickView = views.bricks[i][j];
|
brickView.x = brick.x;
|
||||||
brickView.x = brick.x;
|
brickView.y = brick.y;
|
||||||
brickView.y = brick.y;
|
brickView.visible = brick.alive;
|
||||||
brickView.visible = brick.alive;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|||||||
Reference in New Issue
Block a user