diff --git a/biome.json b/biome.json index 1a1cb10..0029fce 100644 --- a/biome.json +++ b/biome.json @@ -3,8 +3,17 @@ "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, "files": { "includes": ["src/**/*", "*.js", "*.json"] }, "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 120 }, - "linter": { "enabled": true, "rules": { "preset": "recommended" } }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "correctness": { + "noUndeclaredVariables": "error" + } + } + }, "javascript": { + "globals": ["describe", "it", "expect"], "formatter": { "quoteStyle": "single", "semicolons": "always", diff --git a/src/config.js b/src/config.js index 6784004..20c039a 100644 --- a/src/config.js +++ b/src/config.js @@ -10,3 +10,6 @@ export const BALL_INITIAL_ANGLE = 180; export const BRICK_WIDTH = 40; export const BRICK_HEIGHT = 10; + +export const BRICK_ROW_AMOUNT = 5; +export const BRICK_COLUMN_AMOUNT = 20; diff --git a/src/entities/ball/ball.js b/src/entities/ball/ball.js new file mode 100644 index 0000000..0a0c3d4 --- /dev/null +++ b/src/entities/ball/ball.js @@ -0,0 +1,27 @@ +/** + * Класс сущности "мяч" + * @class + */ +export class Ball { + /** + * @param {number} x координата положения мяча по оси X + * @param {number} y координата положения мяча по оси Y + * @param {number} radius положительное числовое значение радиуса мяча + */ + constructor(x, y, radius) { + this.x = x; + this.y = y; + this.horizontalSpeed = 0; + this.verticalSpeed = 0; + this.radius = radius; + } + + /** + * Изменяет координаты в зависимости от скорости и времени + * @param {*} deltaTime изменение времени из Ticker + */ + moveForward(deltaTime) { + this.x += this.horizontalSpeed * deltaTime; + this.y += this.verticalSpeed * deltaTime; + } +} diff --git a/src/entities/brick/brick.js b/src/entities/brick/brick.js new file mode 100644 index 0000000..8151678 --- /dev/null +++ b/src/entities/brick/brick.js @@ -0,0 +1,24 @@ +/** + * Класс сущности "кирпич" + * @class + */ +export class Brick { + /** + * + * @param {number} x координата положения кирпича по оси X + * @param {number} y координата положения кирпича по оси Y + * @param {number} width положительное числовое значение ширины кирпича + * @param {number} height положительное числовое значение высоты кирпича + */ + constructor(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.alive = true; + } + + kill() { + this.alive = false; + } +} diff --git a/src/entities/brick/layBricks/layBricks.js b/src/entities/brick/layBricks/layBricks.js new file mode 100644 index 0000000..9dc722b --- /dev/null +++ b/src/entities/brick/layBricks/layBricks.js @@ -0,0 +1,41 @@ +import { Brick } from '../brick'; + +/** + * Ложит кирпичи по заданым размерам + * @param {number} columnAmount количество кирпичей по оси X, неотрицателное, целое число + * @param {number} rowAmount количество кирпичей по оси Y, неотрицателное, целое число + * @param {number} brickWidth ширина кирпича, неотрицателное число + * @param {number} brickHeight длина кирпича, неотрицателное число + * @returns {Brick[][]} массив с массивами кирпичей + */ +export function layBricks(columnAmount, rowAmount, brickWidth, brickHeight) { + try { + const someArgsArentNumbers = [columnAmount, rowAmount, brickWidth, brickHeight].some( + (arg) => typeof arg !== 'number', + ); + if (someArgsArentNumbers) { + throw new Error('Параметры кладки кирпичей должны являться числами'); + } + + const someArgsLessThanZero = [columnAmount, rowAmount, brickWidth, brickHeight].some((arg) => arg < 0); + if (someArgsLessThanZero) { + throw new Error('Параметры кладки кирпичей должны являться положительными целыми числами'); + } + + const rowsOrColumnsAreFloat = [columnAmount, rowAmount].some((amount) => amount % 1 !== 0); + if (rowsOrColumnsAreFloat) { + throw new Error('Размеры рядов и колонок должны являться целыми числами'); + } + + const bricks = Array.from({ length: rowAmount }).map((_, rowIndex) => + Array.from({ length: columnAmount }).map( + (_, columnIndex) => new Brick(columnIndex * brickWidth, rowIndex * brickHeight, brickWidth, brickHeight), + ), + ); + + return bricks; + } catch (err) { + console.error(err); + return null; + } +} diff --git a/src/entities/brick/layBricks/layBricks.test.js b/src/entities/brick/layBricks/layBricks.test.js new file mode 100644 index 0000000..7e665bb --- /dev/null +++ b/src/entities/brick/layBricks/layBricks.test.js @@ -0,0 +1,59 @@ +import { expect } from 'vitest'; +import { layBricks } from './layBricks'; + +describe('layBricks', () => { + it('Возвращает корректное значение в случае неверного типа параметра', () => { + const wrongType = 'wrong'; + + expect(layBricks(wrongType, 1, 1, 1)).toBeNull(); + expect(layBricks(1, wrongType, 1, 1)).toBeNull(); + expect(layBricks(1, 1, wrongType, 1)).toBeNull(); + expect(layBricks(1, 1, 1, wrongType)).toBeNull(); + }); + + it('Возвращает корректное значение в случае неверных размеров кирпича', () => { + const wrongWidth = -1; + const wrongHeight = -1; + + expect(layBricks(1, 1, wrongWidth, 1)).toBeNull(); + expect(layBricks(1, 1, 1, wrongHeight)).toBeNull(); + }); + + it('Возвращает корректное значение в случае неверных значений рядов и колонок', () => { + const negativeRow = -1; + const negativeColumn = -1; + const decimalRow = 1.5; + const decimalColumn = 1.5; + + expect(layBricks(negativeRow, 1, 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('Возвращает массив корректных размеров', () => { + const columnAmount = 10; + const rowAmount = 5; + + const bricks = layBricks(columnAmount, rowAmount, 1, 1); + expect(bricks.length).toEqual(rowAmount); + for (const row of bricks) { + expect(row.length).toEqual(columnAmount); + } + }); + + it('Задает корректные координаты кирпичам', () => { + const bricks = layBricks(3, 3, 1, 1); + const columnAmount = 10; + const rowAmount = 5; + + const brickss = layBricks(columnAmount, rowAmount, 1, 1); + + for (let i = 0; i < rowAmount; i++) { + for (let j = 0; j < columnAmount; j++) { + expect(brickss[i][j].x).toEqual(j); + expect(brickss[i][j]?.y).toEqual(i); + } + } + }); +}); diff --git a/src/entities/paddle/paddle.js b/src/entities/paddle/paddle.js new file mode 100644 index 0000000..e534883 --- /dev/null +++ b/src/entities/paddle/paddle.js @@ -0,0 +1,36 @@ +/** + * Класс сущности "ракетка" + */ +export class Paddle { + /** + * @param {number} x координата положения ракетки по оси X + * @param {number} y координата положения ракетки по оси Y + * @param {number} width положительное числовое значение ширины ракетки + * @param {number} height положительное числовое значение высоты ракетки + */ + constructor(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + /** + * Изменяет X координату ракетки, ограничивая минимальные и максимальные координаты + * @param {number} x новая X координата + * @param {number} minX минимальное положение на оси X + * @param {number} maxX максимальное положение на оси X + */ + moveTo(x, minX, maxX) { + switch (true) { + case minX !== undefined && x <= minX: + this.x = minX; + return; + case maxX !== undefined && x >= maxX - this.width: + this.x = maxX - this.width; + return; + default: + this.x = x; + } + } +} diff --git a/src/game.js b/src/game.js new file mode 100644 index 0000000..45a8bae --- /dev/null +++ b/src/game.js @@ -0,0 +1,42 @@ +import { + BALL_INITIAL_ANGLE, + BALL_RADIUS, + BALL_SPEED, + BRICK_HEIGHT, + BRICK_WIDTH, + CONTAINER_HEIGHT, + CONTAINER_WIDTH, + PADDLE_HEIGHT, + PADDLE_WIDTH, +} from './config'; +import { Ball } from './entities/ball/ball'; +import { layBricks } from './entities/brick/layBricks/layBricks'; +import { Paddle } from './entities/paddle/paddle'; +import { tick } from './lib/tick/tick'; + +/** + * Класс игры c информацией о всех игровых сущностях + */ +export class Game { + /** + * @param {number} columnAmount количество кирпичей по оси X, неотрицателное, целое число + * @param {number} rowAmount количество кирпичей по оси Y, неотрицателное, целое число + */ + constructor(columnAmount, rowAmount) { + this.ball = new Ball(100, 100, BALL_RADIUS); + this.ball.horizontalSpeed = BALL_SPEED * Math.cos(BALL_INITIAL_ANGLE); + this.ball.verticalSpeed = -1 * BALL_SPEED * Math.sin(BALL_INITIAL_ANGLE); + + this.paddle = new Paddle(0, CONTAINER_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT); + + this.bricks = layBricks(columnAmount, rowAmount, BRICK_WIDTH, BRICK_HEIGHT); + } + + /** + * Изменяет значения сущностей в зависимости от времени + * @param {*} deltaTime изменение времени из Ticker + */ + update(deltaTime) { + tick(this, CONTAINER_WIDTH, CONTAINER_HEIGHT, deltaTime); + } +} diff --git a/src/lib/tick/tick.js b/src/lib/tick/tick.js new file mode 100644 index 0000000..3ca17bc --- /dev/null +++ b/src/lib/tick/tick.js @@ -0,0 +1,100 @@ +import { CONTAINER_HEIGHT, CONTAINER_WIDTH } from '../../config'; +import { Game } from '../../game'; +import { calculateCollision } from '../calculateCollision/calculateCollision'; +import { calculateDirection } from '../calculateDirection/calculateDirection'; + +/** + * Функция для вычисления взаимодействий сущностей игры в зависимости от времени из Ticker + * @param {Game} game экземпляр класса игры + * @param {number} containerWidth ширина игрового контейнера в пикселях + * @param {number} containerHeight высота игрового контейнера в пикселях + * @param {number} deltaTime изменение времени из Ticker + */ +export function tick(game, containerWidth, containerHeight, deltaTime) { + try { + if (!(game instanceof Game)) { + throw new Error('Аргумент game должен быть экземпляром класса игры'); + } + + if ([containerWidth, containerHeight].some((element) => typeof element !== 'number')) { + throw new Error('Значения размеров игрового контейнера должены являться числами'); + } + + if (containerWidth <= 0 || containerHeight <= 0) { + throw new Error('Размеры игрового контейнера должены быть положительными числами'); + } + + if (typeof deltaTime !== 'number' || deltaTime <= 0) { + throw new Error('Значение изменения времени должно быть положительным числом'); + } + + const { ball, paddle, bricks } = game; + + ball.moveForward(deltaTime); + + const leftBoundary = ball.radius; + const rightBoundary = containerWidth - ball.radius; + const topBoundary = ball.radius; + const bottomBoundary = containerHeight - ball.radius; + + // Не даем мячу выйти за границы стен слева / справав и меняем направление + if (ball.x <= leftBoundary || ball.x >= rightBoundary) { + ball.x = ball.x <= leftBoundary ? leftBoundary : rightBoundary; + ball.horizontalSpeed *= -1; + } + + // Не даем мячу выйти за границы стен сверху / снизу и меняем направление + if (ball.y <= topBoundary || ball.y >= bottomBoundary) { + ball.y = ball.y <= topBoundary ? topBoundary : bottomBoundary; + ball.verticalSpeed *= -1; + } + + // Базоввое взаимодействие мяча и кирпича + for (const row of bricks) { + for (const brick of row) { + if (!brick.alive) { + continue; + } + + const ballLeft = ball.x - ball.radius; + const ballRight = ball.x + ball.radius; + const ballTop = ball.y - ball.radius; + const ballBottom = ball.y + ball.radius; + + const brickLeft = brick.x; + const brickRight = brick.x + brick.width; + const brickTop = brick.y; + const brickBottom = brick.y + brick.height; + + const ballObject = { left: ballLeft, right: ballRight, top: ballTop, bottom: ballBottom }; + const brickObject = { left: brickLeft, right: brickRight, top: brickTop, bottom: brickBottom }; + + const isCollided = calculateCollision(ballObject, brickObject); + + if (isCollided) { + const directions = calculateDirection(ballObject, brickObject); + + if (directions !== null) { + ball.horizontalSpeed *= directions[0]; + ball.verticalSpeed *= directions[1]; + brick.kill(); + break; + } + } + } + } + + // Базоввое взаимодействие мяча и ракетки + if ( + ball.verticalSpeed > 0 && + ball.y + ball.radius >= paddle.y && + ball.x >= paddle.x && + ball.x <= paddle.x + paddle.width + ) { + ball.verticalSpeed *= -1; + } + } catch (err) { + console.error(err); + return null; + } +} diff --git a/src/lib/tick/tick.test.js b/src/lib/tick/tick.test.js new file mode 100644 index 0000000..879c79f --- /dev/null +++ b/src/lib/tick/tick.test.js @@ -0,0 +1,78 @@ +import { CONTAINER_HEIGHT, CONTAINER_WIDTH } from '../../config'; +import { Game } from '../../game'; +import { tick } from './tick'; + +describe('tick', () => { + it('Возвращает корректное значние при неверных типах аргументов', () => { + expect(tick(null, 1, 1, 1)).toBeNull(); + expect(tick(1, null, 1, 1)).toBeNull(); + expect(tick(1, 1, null, 1)).toBeNull(); + expect(tick(1, 1, 1, null)).toBeNull(); + }); + + it('Возвращает корректное значние и не изменяет свойства game при неверых размерах контейнера', () => { + const game = new Game(1, 1); + const ballX = game.ball.x; + const ballY = game.ball.y; + expect(tick(game, -1, -1, 1)).toBeNull(); + expect(game.ball.x).toBe(ballX); + expect(game.ball.y).toBe(ballY); + }); + + it('Возвращает корректное значние и не изменяет свойства game при неверном значении времени', () => { + const game = new Game(1, 1); + const ballX = game.ball.x; + const ballY = game.ball.y; + expect(tick(game, 1, 1, -1)).toBeNull(); + expect(game.ball.x).toBe(ballX); + expect(game.ball.y).toBe(ballY); + }); + + it('Меняет направление мяча при столкновении со стеной', () => { + const game = new Game(1, 1); + game.ball.x = 0; + game.ball.horizontalSpeed = -10; + tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1); + expect(game.ball.x).toBe(10); + expect(game.ball.horizontalSpeed).toBe(10); + }); + + it('Меняет направление мяча при столкновении с потолком', () => { + const game = new Game(0, 0); + game.ball.y = 0; + game.ball.verticalSpeed = -10; + tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 1); + expect(game.ball.y).toBe(game.ball.radius); + expect(game.ball.verticalSpeed).toBe(10); + }); + + it('Убивает кирпич при столкновении и отражает мяч', () => { + const game = new Game(1, 1); + const brick = game.bricks[0][0]; + + game.ball.x = brick.x + 1; + game.ball.y = brick.y + brick.height + game.ball.radius + 1; + game.ball.horizontalSpeed = 0; + game.ball.verticalSpeed = -10; + + tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 0.1); + + expect(brick.alive).toBe(false); + expect(game.ball.verticalSpeed).toBe(10); + }); + + it('Убивает только один кирпич за тик', () => { + const game = new Game(2, 1); + const [firstBrick, secondBrick] = game.bricks[0]; + + game.ball.x = firstBrick.x + 1; + game.ball.y = firstBrick.y + firstBrick.height + game.ball.radius + 1; + game.ball.horizontalSpeed = 0; + game.ball.verticalSpeed = -10; + + tick(game, CONTAINER_WIDTH, CONTAINER_HEIGHT, 0.1); + + const killedCount = game.bricks[0].filter((b) => !b.alive).length; + expect(killedCount).toBe(1); + }); +}); diff --git a/src/main.js b/src/main.js index 9754c58..ed9fa34 100644 --- a/src/main.js +++ b/src/main.js @@ -4,15 +4,19 @@ import { BALL_INITIAL_ANGLE, BALL_RADIUS, BALL_SPEED, + BRICK_COLUMN_AMOUNT, BRICK_HEIGHT, + BRICK_ROW_AMOUNT, BRICK_WIDTH, CONTAINER_HEIGHT, CONTAINER_WIDTH, PADDLE_HEIGHT, PADDLE_WIDTH, } from './config'; +import { Game } from './game'; import { calculateCollision } from './lib/calculateCollision/calculateCollision'; import { calculateDirection } from './lib/calculateDirection/calculateDirection'; +import { createGameView, syncronizeViewsWithGame } from './view'; (async () => { // Create a new application @@ -35,95 +39,19 @@ import { calculateDirection } from './lib/calculateDirection/calculateDirection' app.stage.addChild(container); - const paddle = new Graphics().rect(0, CONTAINER_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT).fill('#fff000'); - container.addChild(paddle); + const game = new Game(BRICK_COLUMN_AMOUNT, BRICK_ROW_AMOUNT); + const views = createGameView(game, container); container.on('pointermove', (event) => { const localPosition = container.toLocal(event.global); - - if (localPosition.x < CONTAINER_WIDTH - PADDLE_WIDTH) { - paddle.x = localPosition.x; - } + game.paddle.moveTo(localPosition.x, 0, CONTAINER_WIDTH); }); - const bricksRow = Array.from({ length: Math.floor(CONTAINER_WIDTH / BRICK_WIDTH) }).map((_, index) => { - const brick = new Graphics().rect(0, 0, BRICK_WIDTH, BRICK_HEIGHT).fill('#000fff'); - brick.x = index * BRICK_WIDTH; - brick.y = 1; - container.addChild(brick); - return brick; - }); - - const ball = new Graphics().circle(0, 0, BALL_RADIUS).fill('#ffffff'); - ball.x = 100; - ball.y = 100; - container.addChild(ball); - - const leftBoundary = BALL_RADIUS; - const rightBoundary = CONTAINER_WIDTH - BALL_RADIUS; - const topBoundary = BALL_RADIUS; - const bottomBoundary = CONTAINER_HEIGHT - BALL_RADIUS; - const paddleTop = CONTAINER_HEIGHT - PADDLE_HEIGHT; - const bricksBottom = BRICK_HEIGHT; - - let horizontalSpeed = BALL_SPEED * Math.cos(BALL_INITIAL_ANGLE); - let verticalSpeed = -1 * BALL_SPEED * Math.sin(BALL_INITIAL_ANGLE); + console.log(game.paddle.x, game.paddle.y); app.ticker.add((time) => { - // Базоввое взаимодействие мяча и кирпича - for (let i = bricksRow.length - 1; i >= 0; i--) { - const currentBrick = bricksRow[i]; - const brickLeft = currentBrick.x; - const brickRight = currentBrick.x + BRICK_WIDTH; - const brickTop = currentBrick.y; - const brickBottom = currentBrick.y + BRICK_HEIGHT; - - const ballLeft = ball.x - BALL_RADIUS; - const ballRight = ball.x + BALL_RADIUS; - const ballTop = ball.y - BALL_RADIUS; - const ballBottom = ball.y + BALL_RADIUS; - - const ballObject = { left: ballLeft, right: ballRight, top: ballTop, bottom: ballBottom }; - const brickObject = { left: brickLeft, right: brickRight, top: brickTop, bottom: brickBottom }; - - const isCollided = calculateCollision(ballObject, brickObject); - const directions = calculateDirection(ballObject, brickObject); - - if (isCollided && directions !== null) { - horizontalSpeed *= directions[0]; - verticalSpeed *= directions[1]; - - container.removeChild(currentBrick); - currentBrick.destroy(); - bricksRow.splice(i, 1); - - break; - } - } - - // Не даем мячу выйти за границы стен слева / справав и меняем направление - if (ball.x <= leftBoundary || ball.x >= rightBoundary) { - ball.x = ball.x <= leftBoundary ? leftBoundary : rightBoundary; - horizontalSpeed *= -1; - } - - // Не даем мячу выйти за границы стен сверху / снизу и меняем направление - if (ball.y <= topBoundary || ball.y >= bottomBoundary) { - ball.y = ball.y <= topBoundary ? topBoundary : bottomBoundary; - verticalSpeed *= -1; - } - - // Базоввое взаимодействие мяча и ракетки - if ( - verticalSpeed > 0 && - ball.y + BALL_RADIUS >= paddleTop && - ball.x >= paddle.x && - ball.x <= paddle.x + PADDLE_WIDTH - ) { - verticalSpeed *= -1; - } - - ball.x += horizontalSpeed * time.deltaTime; - ball.y += verticalSpeed * time.deltaTime; + game.update(time.deltaTime); + syncronizeViewsWithGame(views, game); + console.log(game.paddle.x, game.paddle.y); }); })(); diff --git a/src/view.js b/src/view.js new file mode 100644 index 0000000..4aaec1b --- /dev/null +++ b/src/view.js @@ -0,0 +1,92 @@ +import { Container, Graphics } from 'pixi.js'; +import { Ball } from './entities/ball/ball'; +import { Brick } from './entities/brick/brick'; +import { Paddle } from './entities/paddle/paddle'; +import { Game } from './game'; + +/** + * Создает визуальное отображение мяча с помощью Pixi.js + * @param {Ball} ball экземпляр класса мяч + */ +function createBallView(ball) { + return new Graphics().circle(0, 0, ball.radius).fill('#ffffff'); +} + +/** + * Создает визуальное отображение ракетки с помощью Pixi.js + * @param {Paddle} paddle экземпляр класса ракетка + */ +function createPaddleView(paddle) { + return new Graphics().rect(0, 0, paddle.width, paddle.height).fill('#fff000'); +} + +/** + * Создает визуальное отображение кирпича с помощью Pixi.js + * @param {Brick} brick экземпляр класса кирпич + */ +function createBrickView(brick) { + return new Graphics().rect(0, 0, brick.width, brick.height).fill('#000fff'); +} + +/** + * Создает визуальное отображение всех сущностей в игре с помощью Pixi.js и добавляет в контейнер + * @param {Game} game экземпляр класса игра + * @param {Container} container контейнер Pixi.js + */ +export function createGameView(game, container) { + try { + const ball = createBallView(game.ball); + container.addChild(ball); + + const paddle = createPaddleView(game.paddle); + container.addChild(paddle); + + const bricks = game.bricks.map((row) => + row.map((brick) => { + const brickView = createBrickView(brick); + container.addChild(brickView); + return brickView; + }), + ); + + return { + ball, + paddle, + bricks, + }; + } catch (err) { + console.error(err); + return null; + } +} + +/** + * Синхронизирует отображение сущностей Pixi.js с логикой игры (координаты и тд.) + * @param {object} views объект с визуальными отображениями сущностей игры + * @param {Game} game экземпляр класса игра + */ +export function syncronizeViewsWithGame(views, game) { + try { + if (!(game instanceof Game)) { + throw new Error('Аргумент game должен быть экземпляром класса Game'); + } + + views.ball.x = game.ball.x; + views.ball.y = game.ball.y; + + views.paddle.x = game.paddle.x; + views.paddle.y = game.paddle.y; + + for (let i = 0; i < game.bricks.length; i++) { + for (let j = 0; j < game.bricks[i].length; j++) { + const brick = game.bricks[i][j]; + const brickView = views.bricks[i][j]; + brickView.x = brick.x; + brickView.y = brick.y; + brickView.visible = brick.alive; + } + } + } catch (err) { + console.error(err); + } +}