Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
494878c14b | ||
|
|
6302fd2f91 | ||
|
|
4505a846bb | ||
|
|
4d572e8c86 | ||
|
|
8cfe62a064 | ||
|
|
3432d02eaf | ||
|
|
27f230d8f6 | ||
|
|
00cb33b9f9 | ||
|
|
8153233529 | ||
|
|
a16f316b13 | ||
|
|
a11ab8cd5d | ||
|
|
5e9b70e603 | ||
|
|
7a36d23393 | ||
|
|
89bf5289b1 | ||
|
|
5739575200 | ||
|
|
4608e044b0 | ||
|
|
6430470478 | ||
|
|
2dc8735fe6 | ||
|
|
004720acd6 | ||
|
|
2cbff5b924 | ||
|
|
8f593c6a6f |
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/install-state.gz
|
||||
dist
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,21 @@
|
||||
# Arkanoid
|
||||
|
||||
Вариация игры арканоид.
|
||||
- Три уровня нарастающих по сложности (по крайней мере так задумано)
|
||||
- Ракетка двигается по движению курсора
|
||||
- Логика отскока мяча от ракетки реализована через разбиение ракетки на сектора и различным углом отскока
|
||||
- Блоки трех типов: обычный, повышеной прочности и неразбиваемый
|
||||
- Разные очки за обычный блок и блок повышеной прочности
|
||||
- Скорость мяча увеличивается скачками от уровня к уровню и постепенно в течение одного уровня
|
||||
- Из разбитых блоков со случайным шансом выпадают различные типы бонусов: замедление мяча, дополнительная жизнь, увеличение ширины ракетки, добавление двух дополнительных мячей.
|
||||
- Текстуры сущностей взяты из публично доступных бесплатных источников
|
||||
|
||||
## Запуск проекта
|
||||
|
||||
Установка зависимостей: `yarn install`
|
||||
|
||||
Запуск в dev режиме: `yarn dev`
|
||||
|
||||
Сборка: `yarn build`
|
||||
|
||||
Запуск тестов: `yarn test`
|
||||
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 157 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 261 KiB |
|
After Width: | Height: | Size: 278 KiB |
@@ -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;
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||