Skip to content

Commit

Permalink
feat: add Gravity (twilio-labs#1507)
Browse files Browse the repository at this point in the history
* (feat): Add Gravity

* Add Gravity to RunAll
  • Loading branch information
simeydk authored and dkundel committed Nov 2, 2019
1 parent 2eb0a37 commit 9b3854b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
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

0 comments on commit 9b3854b

Please sign in to comment.