Skip to content
This repository has been archived by the owner on Aug 20, 2023. It is now read-only.

(feat): Add Gravity #1507

Merged
merged 3 commits into from
Nov 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions assets/javascript/party-mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ images.forEach(image => image.remove());

let showImages = false;

// add additional 'x-start' and 'y-start' attributes
rects.forEach(rect => {
// add additional 'x-start' and 'y-start' and original index attributes
rects.forEach((rect, i) => {
rect.setAttribute('x-start', rect.getAttribute('x'));
rect.setAttribute('y-start', rect.getAttribute('y'));
rect.setAttribute('key', i)
});

document.addEventListener('keydown', onKeyDown);
Expand All @@ -34,6 +35,7 @@ function onKeyDown(event) {
f: flip,
v: vert,
w: walk,
g: gravity,
l: loop,
a: toggleImages,
p: runAll
Expand Down Expand Up @@ -62,7 +64,7 @@ function runAll() {

isRunningAll = true;

const effects = [order, reset, twist, flip, vert, random, walk, reset];
const effects = [order, reset, twist, flip, vert, random, walk, reset, gravity];

runningTimeout = runFirst(effects);
}
Expand Down Expand Up @@ -125,6 +127,21 @@ function twist() {
transform(({ x, y }) => [390 - y, x]);
}

function gravity() {
// create an array of arrays for every column
const cols = Array.from({length:width},() => [])
rects.forEach(rect => cols[rectToObj(rect).x / 10].push(rect))
cols.forEach(col => {
col.sort((b,a) => rectToObj(a).y - rectToObj(b).y)
col.forEach((rect, i) => {
const y = (height-i-1) * 10
const key = rect.getAttribute('key')
rect.setAttribute('y', y)
images[key].setAttribute('y', y)
})
})
}

function walk() {
latestCommand = walk;
transform(w);
Expand Down Expand Up @@ -161,6 +178,13 @@ const w = ({ x, y }) => {
return [newX, newY];
};

function rectToObj(rect) {
const [x, y, xStart, yStart] = ['x', 'y', 'x-start', 'y-start'].map(
key => rect.getAttribute(key)
);
return {x, y, xStart, yStart};
}

function transform(transformFunction) {
rects.forEach((rect, i) => {
const image = images[i];
Expand Down
1 change: 1 addition & 0 deletions index.njk
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<button class="nes-btn" onClick="flip()">Flip (f)</button>
<button class="nes-btn" onClick="vert()">V-Flip (v)</button>
<button class="nes-btn" onClick="walk()">Walk (w)</button>
<button class="nes-btn" onClick="gravity()">Gravity (g)</button>
</div>
<div>
<button class="nes-btn" onClick="loop()">Loop (l)</button>
Expand Down