Skip to content

Commit

Permalink
task 2 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
guivanrv committed Oct 21, 2021
1 parent 818801d commit 47bc0b4
Showing 1 changed file with 44 additions and 7 deletions.
51 changes: 44 additions & 7 deletions src/scripts/index.js
Expand Up @@ -2,6 +2,7 @@ import '../styles/index.scss';
import * as PIXI from 'pixi.js';

const app = new PIXI.Application();

document.body.appendChild(app.view);
const loader = PIXI.Loader.shared;

Expand All @@ -10,30 +11,66 @@ const animals = ['bear','buffalo','chick','chicken',
'goat', 'gorilla', 'hippo', 'horse', 'monkey', 'moose',
'narwhal', 'owl', 'panda', 'parrot', 'penguin', 'pig',
'rabbit', 'rhino', 'sloth', 'snake', 'walrus', 'whale', 'zebra'
], TILES_OX = 6, TILES_OY = 4, SPRITE_WIDTH = 138, SPRITE_HEIGHT = 138, sprites = [];
], TILES_OX = 6, TILES_OY = 4, SPRITE_WIDTH = 138, SPRITE_HEIGHT = 120, sprites = [];

let selected = undefined;

loader.add(animals.map(str => ({ name: str, url: `public/images/${str}.png` }))).load(
(loader, resources) => {
for (let x = 0; x < TILES_OX; x++) {
sprites[x] = [];
for (let y = 0; y < TILES_OY; y++) {
const randomAnimal = animals[Math.trunc(Math.random() * animals.length)];
const sprite = new PIXI.Sprite(resources[randomAnimal].texture);
sprite.name = randomAnimal;
sprite.anchor.x = 0.5;
sprite.anchor.y = 0.5;
sprite.x = x * SPRITE_WIDTH + SPRITE_WIDTH / 2;
sprite.y = y * SPRITE_HEIGHT + SPRITE_HEIGHT / 2;
sprite.interactive = true;
sprite.buttonMode = true;
app.stage.addChild(sprite);
sprites.push(sprite);
sprites[x][y] = sprite;
// store array position
sprite.customData = { x, y };
sprite.on('pointerdown', (e) => {
if (!selected) {
selected = sprite;
} else {
if (selected === sprite) {
// can't swap element with itself
return;
}
// swap pixi coordinates
const xa = selected.x, ya = selected.y;
selected.x = sprite.x;
selected.y = sprite.y;
sprite.x = xa;
sprite.y = ya;
// swap array position
const positionA = selected.customData, positionB = sprite.customData;
selected.customData = positionB;
sprite.customData = positionA;
sprites[positionA.x][positionA.y] = sprite;
sprites[positionB.x][positionB.y] = selected;
selected = undefined;
}
});
}
}
});


// Listen for frame updates
app.ticker.add(() => {
sprites.forEach((sprite, index) => {
const scale = 1 + 0.1 * Math.sin(Date.now() / (400 + index * 10));
sprite.scale.x = scale;
sprite.scale.y = scale;
})
sprites.forEach((row, x) => {
row.forEach((sprite, y) => {
sprite.scale.set(1, 1);
});
});
if (selected) {
const scale = 1 + 0.1 * Math.sin(Date.now() / 100);
selected.scale.x = scale;
selected.scale.y = scale;
}
});

0 comments on commit 47bc0b4

Please sign in to comment.