Compare commits

..
1 Commits
Author SHA1 Message Date
Ilia Mashkov b7ca56c99c feat(perk): Добавлен таймаут для бонуса увеличения размера ракетки и бонуса замедления скорости мяча
Build and push / build (push) Skipped
Build and push / build (pull_request) Successful in 43s
2026-07-19 18:02:33 +03:00
32 changed files with 53 additions and 308 deletions
-5
View File
@@ -1,5 +0,0 @@
node_modules
.yarn/cache
.yarn/unplugged
.yarn/install-state.gz
dist
-22
View File
@@ -1,22 +0,0 @@
: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
@@ -1,22 +0,0 @@
# 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
@@ -1,21 +0,0 @@
# Arkanoid
Вариация игры арканоид.
- Три уровня нарастающих по сложности (по крайней мере так задумано)
- Ракетка двигается по движению курсора
- Логика отскока мяча от ракетки реализована через разбиение ракетки на сектора и различным углом отскока
- Блоки трех типов: обычный, повышеной прочности и неразбиваемый
- Разные очки за обычный блок и блок повышеной прочности
- Скорость мяча увеличивается скачками от уровня к уровню и постепенно в течение одного уровня
- Из разбитых блоков со случайным шансом выпадают различные типы бонусов: замедление мяча, дополнительная жизнь, увеличение ширины ракетки, добавление двух дополнительных мячей.
- Текстуры сущностей взяты из публично доступных бесплатных источников
## Запуск проекта
Установка зависимостей: `yarn install`
Запуск в dev режиме: `yarn dev`
Сборка: `yarn build`
Запуск тестов: `yarn test`
Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

-3
View File
@@ -15,14 +15,11 @@ export const BALL_SPEED_TIME_STEP = 0.002;
export const BALL_INITIAL_ANGLE = 0; export const BALL_INITIAL_ANGLE = 0;
export const BALL_SPLIT_ANGLE = 20; export const BALL_SPLIT_ANGLE = 20;
export const HEADER_HEIGHT = 30;
export const BRICK_WIDTH = 40; export const BRICK_WIDTH = 40;
export const BRICK_HEIGHT = 10; export const BRICK_HEIGHT = 10;
export const BRICK_ROW_AMOUNT = 5; export const BRICK_ROW_AMOUNT = 5;
export const BRICK_COLUMN_AMOUNT = 20; export const BRICK_COLUMN_AMOUNT = 20;
export const BRICK_POINTS_AMOUNT = { 1: 10, 2: 30 };
export const PERK_WIDTH = 16; export const PERK_WIDTH = 16;
export const PERK_HEIGHT = 16; export const PERK_HEIGHT = 16;
+2 -7
View File
@@ -5,10 +5,9 @@ import { Brick } from '../brick';
* @param {number[][]} levelMap карта уровня в формате массива * @param {number[][]} levelMap карта уровня в формате массива
* @param {number} brickWidth ширина кирпича, неотрицателное число * @param {number} brickWidth ширина кирпича, неотрицателное число
* @param {number} brickHeight длина кирпича, неотрицателное число * @param {number} brickHeight длина кирпича, неотрицателное число
* @param {number} marginTop отступ сверху, неотрицательное число
* @returns {Brick[]} массив кирпичей * @returns {Brick[]} массив кирпичей
*/ */
export function layBricks(levelMap, brickWidth, brickHeight, marginTop = 0) { export function layBricks(levelMap, brickWidth, brickHeight) {
try { try {
if (!(Array.isArray(levelMap) && levelMap.every(Array.isArray))) { if (!(Array.isArray(levelMap) && levelMap.every(Array.isArray))) {
throw new Error('Значение карты уровня должно являться вложенным масивом чисел глубины 2'); throw new Error('Значение карты уровня должно являться вложенным масивом чисел глубины 2');
@@ -22,16 +21,12 @@ export function layBricks(levelMap, brickWidth, brickHeight, marginTop = 0) {
throw new Error('Значения ширины и высоты кирпича должны являться положительными целыми числами'); throw new Error('Значения ширины и высоты кирпича должны являться положительными целыми числами');
} }
if (typeof marginTop !== 'number' || marginTop < 0) {
throw new Error('Значение отступа сверху должно быть неотрицательным числом');
}
const bricks = []; const bricks = [];
for (let i = 0; i < levelMap.length; i++) { for (let i = 0; i < levelMap.length; i++) {
for (let j = 0; j < levelMap[i].length; j++) { for (let j = 0; j < levelMap[i].length; j++) {
if (levelMap[i][j] !== 0) { if (levelMap[i][j] !== 0) {
bricks.push(new Brick(j * brickWidth, marginTop + i * brickHeight, brickWidth, brickHeight, levelMap[i][j])); bricks.push(new Brick(j * brickWidth, i * brickHeight, brickWidth, brickHeight, levelMap[i][j]));
} }
} }
} }
@@ -24,16 +24,6 @@ describe('layBricks', () => {
expect(layBricks(levelMap, 1, 1)).toBeNull(); 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('Возвращает массив корректных размеров', () => { it('Возвращает массив корректных размеров', () => {
const levelMap = [ const levelMap = [
[1, 1, 1, 1, 1], [1, 1, 1, 1, 1],
+2 -4
View File
@@ -8,7 +8,6 @@ import {
BRICK_WIDTH, BRICK_WIDTH,
CONTAINER_HEIGHT, CONTAINER_HEIGHT,
CONTAINER_WIDTH, CONTAINER_WIDTH,
HEADER_HEIGHT,
PADDLE_HEIGHT, PADDLE_HEIGHT,
PADDLE_WIDTH, PADDLE_WIDTH,
PERK_BALL_SPEED_DECREASE, PERK_BALL_SPEED_DECREASE,
@@ -27,7 +26,6 @@ export class Game {
*/ */
constructor(levels) { constructor(levels) {
this.livesAmount = 3; this.livesAmount = 3;
this.score = 0;
this.status = 'in_process'; this.status = 'in_process';
this.levels = levels; this.levels = levels;
this.currentLevel = 0; this.currentLevel = 0;
@@ -35,7 +33,7 @@ export class Game {
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.balls = [new Ball(0, 0, BALL_RADIUS, BALL_SPEED, BALL_INITIAL_ANGLE)]; this.balls = [new Ball(0, 0, BALL_RADIUS, BALL_SPEED, BALL_INITIAL_ANGLE)];
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT, HEADER_HEIGHT); this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT);
this.perks = []; this.perks = [];
this._placeBallOnPaddle(); this._placeBallOnPaddle();
@@ -114,7 +112,7 @@ export class Game {
_proceedToNextLevel() { _proceedToNextLevel() {
this.ball.increaseSpeed(BALL_SPEED_LEVEL_STEP); this.ball.increaseSpeed(BALL_SPEED_LEVEL_STEP);
this._placeBallOnPaddle(); this._placeBallOnPaddle();
this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT, HEADER_HEIGHT); this.bricks = layBricks(this.levels[this.currentLevel], BRICK_WIDTH, BRICK_HEIGHT);
} }
/** /**
@@ -1,4 +1,4 @@
import { BRICK_POINTS_AMOUNT, PERK_DROP_CHANCE, PERK_HEIGHT, PERK_WIDTH } from '../../config'; import { PERK_DROP_CHANCE, PERK_HEIGHT, PERK_WIDTH } from '../../config';
import { Ball } from '../../entities/ball/ball'; import { Ball } from '../../entities/ball/ball';
import { Game } from '../../game'; import { Game } from '../../game';
import { calculateAABBCollision } from '../calculateAABBCollision/calculateAABBCollision'; import { calculateAABBCollision } from '../calculateAABBCollision/calculateAABBCollision';
@@ -55,10 +55,6 @@ export function processBrickCollision(game, ball) {
ball.verticalSpeed *= directions[1]; ball.verticalSpeed *= directions[1];
brick.kill(); brick.kill();
if (!brick.alive) {
game.score += BRICK_POINTS_AMOUNT[brick.type] ?? 0;
}
if (!brick.alive && Math.random() < PERK_DROP_CHANCE) { if (!brick.alive && Math.random() < PERK_DROP_CHANCE) {
const perk = spawnRandomPerk( const perk = spawnRandomPerk(
brick.x + brick.width / 2 - PERK_WIDTH / 2, brick.x + brick.width / 2 - PERK_WIDTH / 2,
+1
View File
@@ -58,6 +58,7 @@ export function updatePerks(game, containerHeight, deltaTime) {
ball.increaseSpeed(-1 * PERK_BALL_SPEED_DECREASE); ball.increaseSpeed(-1 * PERK_BALL_SPEED_DECREASE);
} }
} }
// ponytail: wall-clock timer, game never pauses so no need to tie to deltaTime
setTimeout(() => { setTimeout(() => {
for (const ball of game.balls) { for (const ball of game.balls) {
ball.increaseSpeed(PERK_BALL_SPEED_DECREASE); ball.increaseSpeed(PERK_BALL_SPEED_DECREASE);
+11 -51
View File
@@ -15,52 +15,31 @@ import {
} from './config'; } from './config';
import { LEVELS } from './const/levels'; import { LEVELS } from './const/levels';
import { Game } from './game'; import { Game } from './game';
import { import { createGameView, managePerkViewsLifetime, rebuildBrickViews, syncronizeViewsWithGame } from './view';
createGameView,
managePerkViewsLifetime,
rebuildBrickViews,
syncronizeViewsWithGame,
updateBackgroundView,
} from './view';
(async () => { (async () => {
// Create a new application
const app = new Application(); const app = new Application();
// Initialize the application
await app.init({ background: '#1099bb', width: CONTAINER_WIDTH, height: CONTAINER_HEIGHT }); await app.init({ background: '#1099bb', width: CONTAINER_WIDTH, height: CONTAINER_HEIGHT });
// Append the application canvas to the document body
document.body.appendChild(app.canvas); document.body.appendChild(app.canvas);
// Create and add a container to the stage
const container = new Container({ const container = new Container({
eventMode: 'static', eventMode: 'static',
hitArea: app.screen, hitArea: app.screen,
}); });
container.x = 0; container.x = 0;
container.y = 0; container.y = 0;
app.stage.addChild(container); 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 game = new Game(LEVELS);
const views = createGameView(game, container, textures); const views = createGameView(game, container);
let currentLevel = game.currentLevel; let currentLevel = game.currentLevel;
container.on('pointermove', (event) => { container.on('pointermove', (event) => {
@@ -76,29 +55,10 @@ import {
game.update(time.deltaTime); game.update(time.deltaTime);
if (game.currentLevel !== currentLevel) { if (game.currentLevel !== currentLevel) {
rebuildBrickViews(views, game, container, textures); rebuildBrickViews(views, game, container);
updateBackgroundView(views, game, textures);
currentLevel = game.currentLevel; currentLevel = game.currentLevel;
} }
managePerkViewsLifetime(views, game, container, textures); managePerkViewsLifetime(views, game, container);
syncronizeViewsWithGame(views, game); 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,41 +1 @@
@import "./reset.css"; @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;
}
+36 -118
View File
@@ -1,5 +1,4 @@
import { AnimatedSprite, Container, Graphics, NineSliceSprite, Sprite, Text } from 'pixi.js'; import { Container, Graphics } from 'pixi.js';
import { CONTAINER_HEIGHT, CONTAINER_WIDTH } from './config';
import { Ball } from './entities/ball/ball'; import { Ball } from './entities/ball/ball';
import { Brick } from './entities/brick/brick'; import { Brick } from './entities/brick/brick';
import { Paddle } from './entities/paddle/paddle'; import { Paddle } from './entities/paddle/paddle';
@@ -9,144 +8,77 @@ import { Game } from './game';
/** /**
* Создает визуальное отображение мяча с помощью Pixi.js * Создает визуальное отображение мяча с помощью Pixi.js
* @param {Ball} ball экземпляр класса мяч * @param {Ball} ball экземпляр класса мяч
* @param {object} textures объект с текстурами для визуального отображения
*/ */
function createBallView(ball, textures) { function createBallView(ball) {
const ballFrames = [ return new Graphics().circle(0, 0, ball.radius).fill('#ffffff');
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 * Создает визуальное отображение ракетки с помощью Pixi.js
* @param {Paddle} paddle экземпляр класса ракетка * @param {Paddle} paddle экземпляр класса ракетка
* @param {object} textures объект с текстурами для визуального отображения
*/ */
function createPaddleView(paddle, textures) { function createPaddleView(paddle) {
const texture = textures['/sprites/paddle.png']; return new Graphics().rect(0, 0, paddle.width, paddle.height).fill('#fff000');
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 * Создает визуальное отображение кирпича с помощью Pixi.js
* @param {Brick} brick экземпляр класса кирпич * @param {Brick} brick экземпляр класса кирпич
* @returns {Graphics} графическое отображение кирпича * @returns {Graphics} графическое отображение кирпича
* @param {object} textures объект с текстурами для визуального отображения
*/ */
function createBrickView(brick, textures) { function createBrickView(brick) {
const bricksTextures = [ const brickView = new Graphics().rect(0, 0, brick.width, brick.height);
textures['/sprites/block_1.png'],
textures['/sprites/block_2.png'],
textures['/sprites/block_3.png'],
];
const brickSprite = new Sprite(bricksTextures[brick.type - 1]); switch (brick.type) {
brickSprite.width = brick.width; case 2:
brickSprite.height = brick.height; return brickView.fill('#00ff00');
case 3:
return brickSprite; return brickView.fill('#ff00ff');
case 1:
default:
return brickView.fill('#000fff');
}
} }
/** /**
* Создает визуальное отображение бонуса с помощью Pixi.js * Создает визуальное отображение бонуса с помощью Pixi.js
* @param {Perk} perk экземпляр класса бонус * @param {Perk} perk экземпляр класса бонус
* @returns {Graphics} графическое отображение бонуса * @returns {Graphics} графическое отображение бонуса
* @param {object} textures текстуры блоков
*/ */
function createPerkView(perk, textures) { function createPerkView(perk) {
let texture; const perkView = new Graphics().rect(0, 0, perk.width, perk.height);
switch (perk.type) { switch (perk.type) {
case 'slow': case 'slow':
texture = textures['/sprites/perk_1.png']; return perkView.fill('#00ffff');
break;
case 'wide': case 'wide':
texture = textures['/sprites/perk_2.png']; return perkView.fill('#0f0f0f');
break;
case 'life': case 'life':
texture = textures['/sprites/perk_3.png']; return perkView.fill('#f0f0f0');
break;
case 'clone':
texture = textures['/sprites/perk_3.png'];
break;
default: default:
texture = textures['/sprites/perk_1.png']; return perkView.fill('#ffffff');
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 и добавляет в контейнер * Создает визуальное отображение всех сущностей в игре с помощью Pixi.js и добавляет в контейнер
* @param {Game} game экземпляр класса игра * @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js * @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/ */
export function createGameView(game, container, textures) { export function createGameView(game, container) {
try { 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(); const balls = new Map();
for (const ball of game.balls) { for (const ball of game.balls) {
const ballView = createBallView(ball, textures); const ballView = createBallView(ball);
container.addChild(ballView); container.addChild(ballView);
balls.set(ball, ballView); balls.set(ball, ballView);
} }
const paddle = createPaddleView(game.paddle, textures); const paddle = createPaddleView(game.paddle);
container.addChild(paddle); container.addChild(paddle);
const bricks = game.bricks.map((brick) => { const bricks = game.bricks.map((brick) => {
const brickView = createBrickView(brick, textures); const brickView = createBrickView(brick);
container.addChild(brickView); container.addChild(brickView);
return brickView; return brickView;
}); });
@@ -154,8 +86,6 @@ export function createGameView(game, container, textures) {
const perks = new Map(); const perks = new Map();
return { return {
background,
header,
balls, balls,
paddle, paddle,
bricks, bricks,
@@ -172,12 +102,13 @@ export function createGameView(game, container, textures) {
* @param {object} views объект с визуальными отображениями сущностей игры * @param {object} views объект с визуальными отображениями сущностей игры
* @param {Game} game экземпляр класса игра * @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js * @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/ */
export function managePerkViewsLifetime(views, game, container, textures) { export function managePerkViewsLifetime(views, game, container) {
// Изменяем ширину отображения ракетки основываясь на aspect ratio по оси X и ширине ракетки if (views.paddle.width !== game.paddle.width) {
if (views.paddle.width * views.paddle.scale.x !== game.paddle.width) { container.removeChild(views.paddle);
views.paddle.width = game.paddle.width / views.paddle.scale.x; views.paddle.destroy();
views.paddle = createPaddleView(game.paddle);
container.addChild(views.paddle);
} }
for (const [ball, ballView] of views.balls) { for (const [ball, ballView] of views.balls) {
@@ -190,7 +121,7 @@ export function managePerkViewsLifetime(views, game, container, textures) {
for (const ball of game.balls) { for (const ball of game.balls) {
if (!views.balls.has(ball)) { if (!views.balls.has(ball)) {
const ballView = createBallView(ball, textures); const ballView = createBallView(ball);
container.addChild(ballView); container.addChild(ballView);
views.balls.set(ball, ballView); views.balls.set(ball, ballView);
} }
@@ -206,7 +137,7 @@ export function managePerkViewsLifetime(views, game, container, textures) {
for (const perk of game.perks) { for (const perk of game.perks) {
if (!views.perks.has(perk)) { if (!views.perks.has(perk)) {
const perkView = createPerkView(perk, textures); const perkView = createPerkView(perk);
container.addChild(perkView); container.addChild(perkView);
views.perks.set(perk, perkView); views.perks.set(perk, perkView);
} }
@@ -224,8 +155,6 @@ export function syncronizeViewsWithGame(views, game) {
throw new Error('Аргумент game должен быть экземпляром класса Game'); throw new Error('Аргумент game должен быть экземпляром класса Game');
} }
views.header.text = `Уровень: ${game.currentLevel + 1} Количество жизней: ${game.livesAmount} Очки: ${game.score}`;
for (const ball of game.balls) { for (const ball of game.balls) {
const ballView = views.balls.get(ball); const ballView = views.balls.get(ball);
ballView.x = ball.x; ballView.x = ball.x;
@@ -253,31 +182,20 @@ 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 {object} views объект с визуальными отображениями сущностей игры
* @param {Game} game экземпляр класса игра * @param {Game} game экземпляр класса игра
* @param {Container} container экземпляр класса контейнер Pixi.js * @param {Container} container экземпляр класса контейнер Pixi.js
* @param {object} textures объект с текстурами для визуального отображения
*/ */
export function rebuildBrickViews(views, game, container, textures) { export function rebuildBrickViews(views, game, container) {
for (const brickView of views.bricks) { for (const brickView of views.bricks) {
container.removeChild(brickView); container.removeChild(brickView);
brickView.destroy(); brickView.destroy();
} }
views.bricks = game.bricks.map((brick) => { views.bricks = game.bricks.map((brick) => {
const brickView = createBrickView(brick, textures); const brickView = createBrickView(brick);
container.addChild(brickView); container.addChild(brickView);
return brickView; return brickView;
}); });