Compare commits

...
23 Commits
Author SHA1 Message Date
ilia 494878c14b Merge pull request 'chore: Добавлено описание проекта в README' (#10) from chore/readme into main
Build and push / build (push) Successful in 40s
Reviewed-on: #10
2026-07-21 09:02:28 +00:00
Ilia Mashkov 6302fd2f91 chore: Добавлено описание проекта в README
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 40s
2026-07-21 12:00:53 +03:00
ilia 4505a846bb Merge pull request 'Feature/enhanced look' (#9) from feature/enhanced-look into main
Build and push / build (push) Successful in 41s
Reviewed-on: #9
2026-07-21 08:45:13 +00:00
Ilia Mashkov 4d572e8c86 feat: Добавлен счет игры. Очки отличаются для разных типов блоков. Счет в хедере и в окне при завершении игры
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 41s
2026-07-21 11:41:15 +03:00
Ilia Mashkov 8cfe62a064 fix: Исправлен эффект увеличения ширины ракетки, работа NineSliceSprite 2026-07-21 11:25:00 +03:00
Ilia Mashkov 3432d02eaf feat: Добавлена смена фона игры при смене уровня 2026-07-21 10:26:48 +03:00
Ilia Mashkov 27f230d8f6 feat: Добавлена анимация для текстуры мяча 2026-07-21 09:36:59 +03:00
ilia 00cb33b9f9 Merge pull request 'chore: Добавлен Dockerfile и Caddyfile' (#8) from chore/docker into main
Build and push / build (push) Successful in 40s
Reviewed-on: #8
2026-07-20 07:57:53 +00:00
Ilia Mashkov 8153233529 chore: Добавлен Dockerfile и Caddyfile
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 41s
2026-07-20 10:48:25 +03:00
ilia a16f316b13 Merge pull request 'feat: Добавлено сообщение об окончании игры и кнопка перезагрузки' (#7) from feature/notifications into main
Build and push / build (push) Successful in 39s
Reviewed-on: #7
2026-07-20 07:27:23 +00:00
Ilia Mashkov a11ab8cd5d feat: Добавлено сообщение об окончании игры и кнопка перезагрузки
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 41s
2026-07-20 10:22:03 +03:00
ilia 5e9b70e603 Merge pull request 'Feature/appearance' (#6) from feature/appearance into main
Build and push / build (push) Successful in 40s
Reviewed-on: #6
2026-07-20 07:09:10 +00:00
Ilia Mashkov 7a36d23393 refactor: Изменен способ передачи текстур в функции создания спрайтов, исправлен баг с отсутствием аргумента
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 43s
2026-07-20 10:01:26 +03:00
Ilia Mashkov 89bf5289b1 fix: Добавлен пропущеный аргумент при создании клонов мяча 2026-07-20 09:55:54 +03:00
Ilia Mashkov 5739575200 feat: Добавлена текстуры бонусов разных типов 2026-07-20 09:52:59 +03:00
Ilia Mashkov 4608e044b0 feat: Добавлена текстуры блоков разных типов 2026-07-20 09:17:23 +03:00
Ilia Mashkov 6430470478 feat: Добавлена текстура ракетки и обновлена логика изменения ширины при подборе бонуса 2026-07-20 09:06:38 +03:00
Ilia Mashkov 2dc8735fe6 feat: Добавлена текстура фонового изображения 2026-07-20 08:43:24 +03:00
Ilia Mashkov 004720acd6 feat: Добавлены файлы текстуры мяча, Graphics заменен на Sprite с текстурой 2026-07-19 21:11:56 +03:00
Ilia Mashkov 2cbff5b924 feat: Добавлен хедер с информацией о текущем уровне и количестве оставшихся жизней 2026-07-19 19:19:24 +03:00
Ilia Mashkov 8f593c6a6f feat: Контейнер с игрой растянут на весь экран 2026-07-19 18:58:25 +03:00
ilia afe028430f Merge pull request 'Feature/advanced game mechanics' (#5) from feature/advanced-game-mechanics into main
Build and push / build (push) Successful in 40s
Reviewed-on: #5
2026-07-19 15:09:20 +00:00
Ilia Mashkov 48fb992d04 feat(perk): Добавлен таймаут для бонуса увеличения размера ракетки и бонуса замедления скорости мяча
Build and push / build (push) Skipped
2026-07-19 18:02:33 +03:00
32 changed files with 325 additions and 53 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules
.yarn/cache
.yarn/unplugged
.yarn/install-state.gz
dist
+22
View File
@@ -0,0 +1,22 @@
:3000 {
root * /usr/share/caddy
encode {
zstd
gzip
match {
header Content-Type text/*
header Content-Type application/javascript*
header Content-Type application/json*
header Content-Type image/svg+xml*
}
}
@assets path /assets/*
header @assets Cache-Control "public, max-age=31536000, immutable"
@html path / /index.html
header @html Cache-Control "no-cache"
file_server
}
+22
View File
@@ -0,0 +1,22 @@
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
# Enable Corepack so we can use Yarn v4 (pinned to match lockfile)
RUN corepack enable && corepack prepare yarn@4.11.0 --activate
# Force Yarn to use node_modules instead of PnP
ENV YARN_NODE_LINKER=node-modules
COPY package.json yarn.lock ./
RUN yarn install --immutable
COPY . .
RUN yarn build && ls -la dist
# Production stage - Caddy
FROM caddy:2-alpine
WORKDIR /usr/share/caddy
# Copy built static files from the builder stage
COPY --from=builder /app/dist .
# Copy our local Caddyfile config
COPY Caddyfile /etc/caddy/Caddyfile
EXPOSE 3000
# Start caddy using the config file
CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
+21
View File
@@ -0,0 +1,21 @@
# Arkanoid
Вариация игры арканоид.
- Три уровня нарастающих по сложности (по крайней мере так задумано)
- Ракетка двигается по движению курсора
- Логика отскока мяча от ракетки реализована через разбиение ракетки на сектора и различным углом отскока
- Блоки трех типов: обычный, повышеной прочности и неразбиваемый
- Разные очки за обычный блок и блок повышеной прочности
- Скорость мяча увеличивается скачками от уровня к уровню и постепенно в течение одного уровня
- Из разбитых блоков со случайным шансом выпадают различные типы бонусов: замедление мяча, дополнительная жизнь, увеличение ширины ракетки, добавление двух дополнительных мячей.
- Текстуры сущностей взяты из публично доступных бесплатных источников
## Запуск проекта
Установка зависимостей: `yarn install`
Запуск в dev режиме: `yarn dev`
Сборка: `yarn build`
Запуск тестов: `yarn test`
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

+4
View File
@@ -15,11 +15,14 @@ export const BALL_SPEED_TIME_STEP = 0.002;
export const BALL_INITIAL_ANGLE = 0;
export const BALL_SPLIT_ANGLE = 20;
export const HEADER_HEIGHT = 30;
export const BRICK_WIDTH = 40;
export const BRICK_HEIGHT = 10;
export const BRICK_ROW_AMOUNT = 5;
export const BRICK_COLUMN_AMOUNT = 20;
export const BRICK_POINTS_AMOUNT = { 1: 10, 2: 30 };
export const PERK_WIDTH = 16;
export const PERK_HEIGHT = 16;
@@ -27,3 +30,4 @@ export const PERK_FALL_SPEED = 3;
export const PERK_DROP_CHANCE = 0.3;
export const PERK_BALL_SPEED_DECREASE = 2;
export const PERK_TYPES = ['slow', 'wide', 'life', 'clone'];
export const PERK_DURATION_SEC = 20;
+7 -2
View File
@@ -5,9 +5,10 @@ import { Brick } from '../brick';
* @param {number[][]} levelMap карта уровня в формате массива
* @param {number} brickWidth ширина кирпича, неотрицателное число
* @param {number} brickHeight длина кирпича, неотрицателное число
* @param {number} marginTop отступ сверху, неотрицательное число
* @returns {Brick[]} массив кирпичей
*/
export function layBricks(levelMap, brickWidth, brickHeight) {
export function layBricks(levelMap, brickWidth, brickHeight, marginTop = 0) {
try {
if (!(Array.isArray(levelMap) && levelMap.every(Array.isArray))) {
throw new Error('Значение карты уровня должно являться вложенным масивом чисел глубины 2');
@@ -21,12 +22,16 @@ export function layBricks(levelMap, brickWidth, brickHeight) {
throw new Error('Значения ширины и высоты кирпича должны являться положительными целыми числами');
}
if (typeof marginTop !== 'number' || marginTop < 0) {
throw new Error('Значение отступа сверху должно быть неотрицательным числом');
}
const bricks = [];
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, levelMap[i][j]));
bricks.push(new Brick(j * brickWidth, marginTop + i * brickHeight, brickWidth, brickHeight, levelMap[i][j]));
}
}
}
@@ -24,6 +24,16 @@ describe('layBricks', () => {
expect(layBricks(levelMap, 1, 1)).toBeNull();
});
it('Возвращает корректное значение в случае некоректного отступа', () => {
const levelMap = [
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
];
expect(layBricks(levelMap, 1, 1, -1)).toBeNull();
});
it('Возвращает массив корректных размеров', () => {
const levelMap = [
[1, 1, 1, 1, 1],
+4 -2
View File
@@ -8,6 +8,7 @@ import {
BRICK_WIDTH,
CONTAINER_HEIGHT,
CONTAINER_WIDTH,
HEADER_HEIGHT,
PADDLE_HEIGHT,
PADDLE_WIDTH,
PERK_BALL_SPEED_DECREASE,
@@ -26,6 +27,7 @@ export class Game {
*/
constructor(levels) {
this.livesAmount = 3;
this.score = 0;
this.status = 'in_process';
this.levels = levels;
this.currentLevel = 0;
@@ -33,7 +35,7 @@ export class Game {
this.paddle = new Paddle(0, CONTAINER_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT);
this.balls = [new Ball(0, 0, BALL_RADIUS, BALL_SPEED, BALL_INITIAL_ANGLE)];
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT);
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT, HEADER_HEIGHT);
this.perks = [];
this._placeBallOnPaddle();
@@ -112,7 +114,7 @@ export class Game {
_proceedToNextLevel() {
this.ball.increaseSpeed(BALL_SPEED_LEVEL_STEP);
this._placeBallOnPaddle();
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT);
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT, HEADER_HEIGHT);
}
/**
@@ -1,4 +1,4 @@
import { PERK_DROP_CHANCE, PERK_HEIGHT, PERK_WIDTH } from '../../config';
import { BRICK_POINTS_AMOUNT, PERK_DROP_CHANCE, PERK_HEIGHT, PERK_WIDTH } from '../../config';
import { Ball } from '../../entities/ball/ball';
import { Game } from '../../game';
import { calculateAABBCollision } from '../calculateAABBCollision/calculateAABBCollision';
@@ -55,6 +55,10 @@ export function processBrickCollision(game, ball) {
ball.verticalSpeed *= directions[1];
brick.kill();
if (!brick.alive) {
game.score += BRICK_POINTS_AMOUNT[brick.type] ?? 0;
}
if (!brick.alive && Math.random() < PERK_DROP_CHANCE) {
const perk = spawnRandomPerk(
brick.x + brick.width / 2 - PERK_WIDTH / 2,
+16 -1
View File
@@ -1,4 +1,11 @@
import { BALL_SPLIT_ANGLE, CONTAINER_WIDTH, PADDLE_WIDE_WIDTH, PERK_BALL_SPEED_DECREASE } from '../../config';
import {
BALL_SPLIT_ANGLE,
CONTAINER_WIDTH,
PADDLE_WIDE_WIDTH,
PADDLE_WIDTH,
PERK_BALL_SPEED_DECREASE,
PERK_DURATION_SEC,
} from '../../config';
import { clone } from '../../entities/ball/clone/clone';
import { Game } from '../../game';
import { calculateAABBCollision } from '../calculateAABBCollision/calculateAABBCollision';
@@ -51,10 +58,18 @@ export function updatePerks(game, containerHeight, deltaTime) {
ball.increaseSpeed(-1 * PERK_BALL_SPEED_DECREASE);
}
}
setTimeout(() => {
for (const ball of game.balls) {
ball.increaseSpeed(PERK_BALL_SPEED_DECREASE);
}
}, PERK_DURATION_SEC * 1000);
break;
case 'wide':
paddle.width = PADDLE_WIDE_WIDTH;
paddle.moveTo(paddle.x, 0, CONTAINER_WIDTH);
setTimeout(() => {
paddle.width = PADDLE_WIDTH;
}, PERK_DURATION_SEC * 1000);
break;
case 'life':
game.livesAmount += 1;
+51 -11
View File
@@ -15,31 +15,52 @@ import {
} from './config';
import { LEVELS } from './const/levels';
import { Game } from './game';
import { createGameView, managePerkViewsLifetime, rebuildBrickViews, syncronizeViewsWithGame } from './view';
import {
createGameView,
managePerkViewsLifetime,
rebuildBrickViews,
syncronizeViewsWithGame,
updateBackgroundView,
} from './view';
(async () => {
// Create a new application
const app = new Application();
// Initialize the application
await app.init({ background: '#1099bb', width: CONTAINER_WIDTH, height: CONTAINER_HEIGHT });
// Append the application canvas to the document body
document.body.appendChild(app.canvas);
// Create and add a container to the stage
const container = new Container({
eventMode: 'static',
hitArea: app.screen,
});
container.x = 0;
container.y = 0;
app.stage.addChild(container);
const textures = await Assets.load([
'/sprites/fire_ball_1.png',
'/sprites/fire_ball_2.png',
'/sprites/fire_ball_3.png',
'/sprites/fire_ball_4.png',
'/sprites/fire_ball_5.png',
'/sprites/fire_ball_6.png',
'/sprites/fire_ball_7.png',
'/sprites/fire_ball_8.png',
'/sprites/background_1.png',
'/sprites/background_2.png',
'/sprites/background_3.png',
'/sprites/paddle.png',
'/sprites/block_1.png',
'/sprites/block_2.png',
'/sprites/block_3.png',
'/sprites/perk_1.png',
'/sprites/perk_2.png',
'/sprites/perk_3.png',
'/sprites/perk_4.png',
]);
const game = new Game(LEVELS);
const views = createGameView(game, container);
const views = createGameView(game, container, textures);
let currentLevel = game.currentLevel;
container.on('pointermove', (event) => {
@@ -55,10 +76,29 @@ import { createGameView, managePerkViewsLifetime, rebuildBrickViews, syncronizeV
game.update(time.deltaTime);
if (game.currentLevel !== currentLevel) {
rebuildBrickViews(views, game, container);
rebuildBrickViews(views, game, container, textures);
updateBackgroundView(views, game, textures);
currentLevel = game.currentLevel;
}
managePerkViewsLifetime(views, game, container);
managePerkViewsLifetime(views, game, container, textures);
syncronizeViewsWithGame(views, game);
if (game.status === 'over' || game.status === 'completed') {
showEndScreen(game.status === 'completed' ? 'Победа!' : 'Игра окончена!', game.score);
app.ticker.stop();
}
});
})();
/**
* Показывает финальный экран с сообщением и кнопкой рестарта (перезагрузка страницы).
* @param {string} message текст результата игры
* @param {number} score итоговые очки
*/
function showEndScreen(message, score) {
const overlay = document.createElement('div');
overlay.className = 'end-screen';
overlay.innerHTML = `<p>${message}</p><p>Очки: ${score}</p><button class="button" type="button">Начать заново</button>`;
overlay.querySelector('button').addEventListener('click', () => location.reload());
document.body.appendChild(overlay);
}
+40
View File
@@ -1 +1,41 @@
@import "./reset.css";
body {
min-height: 100vh;
}
canvas {
width: 100vw;
height: 100vh;
display: block;
object-fit: contain;
}
.end-screen {
position: fixed;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
background: rgba(0, 0, 0, 0.6);
color: #fff;
font-size: 3rem;
font-family: sans-serif;
font-weight: 700;
}
.end-screen button {
color: #ffffff;
font-size: 1.5rem;
font-family: sans-serif;
padding: 0.5rem 1.5rem;
cursor: pointer;
transition: all 0.2s ease-out;
}
.end-screen button:hover {
color: #ffffff88;
}
+118 -36
View File
@@ -1,4 +1,5 @@
import { Container, Graphics } from 'pixi.js';
import { AnimatedSprite, Container, Graphics, NineSliceSprite, Sprite, Text } from 'pixi.js';
import { CONTAINER_HEIGHT, CONTAINER_WIDTH } from './config';
import { Ball } from './entities/ball/ball';
import { Brick } from './entities/brick/brick';
import { Paddle } from './entities/paddle/paddle';
@@ -8,77 +9,144 @@ import { Game } from './game';
/**
* Создает визуальное отображение мяча с помощью Pixi.js
* @param {Ball} ball экземпляр класса мяч
* @param {object} textures объект с текстурами для визуального отображения
*/
function createBallView(ball) {
return new Graphics().circle(0, 0, ball.radius).fill('#ffffff');
function createBallView(ball, textures) {
const ballFrames = [
textures['/sprites/fire_ball_1.png'],
textures['/sprites/fire_ball_2.png'],
textures['/sprites/fire_ball_3.png'],
textures['/sprites/fire_ball_4.png'],
textures['/sprites/fire_ball_5.png'],
textures['/sprites/fire_ball_6.png'],
textures['/sprites/fire_ball_7.png'],
textures['/sprites/fire_ball_8.png'],
];
const ballSprite = new AnimatedSprite(ballFrames);
ballSprite.animationSpeed = 0.15;
ballSprite.anchor.set(0.5);
ballSprite.width = ball.radius * 2;
ballSprite.height = ball.radius * 2;
ballSprite.play();
return ballSprite;
}
/**
* Создает визуальное отображение ракетки с помощью Pixi.js
* @param {Paddle} paddle экземпляр класса ракетка
* @param {object} textures объект с текстурами для визуального отображения
*/
function createPaddleView(paddle) {
return new Graphics().rect(0, 0, paddle.width, paddle.height).fill('#fff000');
function createPaddleView(paddle, textures) {
const texture = textures['/sprites/paddle.png'];
const paddleSprite = new NineSliceSprite({ texture, leftWidth: 150, rightWidth: 150, topHeight: 0, bottomHeight: 0 });
const paddleAspectRatio = paddle.height / texture.height;
paddleSprite.scale.set(paddleAspectRatio);
paddleSprite.width = paddle.width / paddleAspectRatio;
return paddleSprite;
}
/**
* Создает визуальное отображение кирпича с помощью Pixi.js
* @param {Brick} brick экземпляр класса кирпич
* @returns {Graphics} графическое отображение кирпича
* @param {object} textures объект с текстурами для визуального отображения
*/
function createBrickView(brick) {
const brickView = new Graphics().rect(0, 0, brick.width, brick.height);
function createBrickView(brick, textures) {
const bricksTextures = [
textures['/sprites/block_1.png'],
textures['/sprites/block_2.png'],
textures['/sprites/block_3.png'],
];
switch (brick.type) {
case 2:
return brickView.fill('#00ff00');
case 3:
return brickView.fill('#ff00ff');
case 1:
default:
return brickView.fill('#000fff');
}
const brickSprite = new Sprite(bricksTextures[brick.type - 1]);
brickSprite.width = brick.width;
brickSprite.height = brick.height;
return brickSprite;
}
/**
* Создает визуальное отображение бонуса с помощью Pixi.js
* @param {Perk} perk экземпляр класса бонус
* @returns {Graphics} графическое отображение бонуса
* @param {object} textures текстуры блоков
*/
function createPerkView(perk) {
const perkView = new Graphics().rect(0, 0, perk.width, perk.height);
function createPerkView(perk, textures) {
let texture;
switch (perk.type) {
case 'slow':
return perkView.fill('#00ffff');
texture = textures['/sprites/perk_1.png'];
break;
case 'wide':
return perkView.fill('#0f0f0f');
texture = textures['/sprites/perk_2.png'];
break;
case 'life':
return perkView.fill('#f0f0f0');
texture = textures['/sprites/perk_3.png'];
break;
case 'clone':
texture = textures['/sprites/perk_3.png'];
break;
default:
return perkView.fill('#ffffff');
texture = textures['/sprites/perk_1.png'];
break;
}
const perkSprite = new Sprite(texture);
perkSprite.width = perk.width;
perkSprite.height = perk.height;
return perkSprite;
}
/**
* Возвращает текстуру фона для текущего уровня или дефолтную текстуру фона
* @param {Game} game экземпляр класса игра
* @param {object} textures объект с текстурами для визуального отображения
*/
function backgroundTextureForLevel(game, textures) {
const levelBackground = textures[`/sprites/background_${game.currentLevel + 1}.png`];
if (!levelBackground) {
return textures['/sprites/background_1.png'];
}
return levelBackground;
}
/**
* Создает визуальное отображение всех сущностей в игре с помощью Pixi.js и добавляет в контейнер
* @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/
export function createGameView(game, container) {
export function createGameView(game, container, textures) {
try {
const background = new Sprite(backgroundTextureForLevel(game, textures));
background.width = CONTAINER_WIDTH;
background.height = CONTAINER_HEIGHT;
container.addChildAt(background, 0);
const header = new Text({ style: { fill: '#ffffff', fontSize: 16 } });
header.x = 8;
header.y = 8;
container.addChild(header);
const balls = new Map();
for (const ball of game.balls) {
const ballView = createBallView(ball);
const ballView = createBallView(ball, textures);
container.addChild(ballView);
balls.set(ball, ballView);
}
const paddle = createPaddleView(game.paddle);
const paddle = createPaddleView(game.paddle, textures);
container.addChild(paddle);
const bricks = game.bricks.map((brick) => {
const brickView = createBrickView(brick);
const brickView = createBrickView(brick, textures);
container.addChild(brickView);
return brickView;
});
@@ -86,6 +154,8 @@ export function createGameView(game, container) {
const perks = new Map();
return {
background,
header,
balls,
paddle,
bricks,
@@ -102,13 +172,12 @@ export function createGameView(game, container) {
* @param {object} views объект с визуальными отображениями сущностей игры
* @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/
export function managePerkViewsLifetime(views, game, container) {
if (views.paddle.width !== game.paddle.width) {
container.removeChild(views.paddle);
views.paddle.destroy();
views.paddle = createPaddleView(game.paddle);
container.addChild(views.paddle);
export function managePerkViewsLifetime(views, game, container, textures) {
// Изменяем ширину отображения ракетки основываясь на aspect ratio по оси X и ширине ракетки
if (views.paddle.width * views.paddle.scale.x !== game.paddle.width) {
views.paddle.width = game.paddle.width / views.paddle.scale.x;
}
for (const [ball, ballView] of views.balls) {
@@ -121,7 +190,7 @@ export function managePerkViewsLifetime(views, game, container) {
for (const ball of game.balls) {
if (!views.balls.has(ball)) {
const ballView = createBallView(ball);
const ballView = createBallView(ball, textures);
container.addChild(ballView);
views.balls.set(ball, ballView);
}
@@ -137,7 +206,7 @@ export function managePerkViewsLifetime(views, game, container) {
for (const perk of game.perks) {
if (!views.perks.has(perk)) {
const perkView = createPerkView(perk);
const perkView = createPerkView(perk, textures);
container.addChild(perkView);
views.perks.set(perk, perkView);
}
@@ -155,6 +224,8 @@ export function syncronizeViewsWithGame(views, game) {
throw new Error('Аргумент game должен быть экземпляром класса Game');
}
views.header.text = `Уровень: ${game.currentLevel + 1} Количество жизней: ${game.livesAmount} Очки: ${game.score}`;
for (const ball of game.balls) {
const ballView = views.balls.get(ball);
ballView.x = ball.x;
@@ -182,20 +253,31 @@ export function syncronizeViewsWithGame(views, game) {
}
}
/**
* Меняет текстуру фона под текущий уровень игры.
* @param {object} views объект с визуальными отображениями сущностей игры
* @param {Game} game экземпляр класса игра
* @param {object} textures объект с текстурами для визуального отображения
*/
export function updateBackgroundView(views, game, textures) {
views.background.texture = backgroundTextureForLevel(game, textures);
}
/**
* Пересоздает отображения кирпичей под текущий уровень игры.
* @param {object} views объект с визуальными отображениями сущностей игры
* @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/
export function rebuildBrickViews(views, game, container) {
export function rebuildBrickViews(views, game, container, textures) {
for (const brickView of views.bricks) {
container.removeChild(brickView);
brickView.destroy();
}
views.bricks = game.bricks.map((brick) => {
const brickView = createBrickView(brick);
const brickView = createBrickView(brick, textures);
container.addChild(brickView);
return brickView;
});