Skip to content

Instantly share code, notes, and snippets.

@embarq
Created January 4, 2018 12:16
Show Gist options
  • Select an option

  • Save embarq/a06139725c25c5cda798cb68c78ebb6c to your computer and use it in GitHub Desktop.

Select an option

Save embarq/a06139725c25c5cda798cb68c78ebb6c to your computer and use it in GitHub Desktop.
function rand(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function placeRandom(field) {
field[rand(0, 16)] = rand(0, 100) > 50 ? 2 : 4;
}
function create(pattern = null) {
if (pattern != null) {
return pattern
.split('\n')
.filter(x => x !== '')
.join('|')
.split('|')
.map(x => x === '*' ? null : x);
}
const field = new Array(16).fill(null);
placeRandom(field);
placeRandom(field);
return field;
}
function getCol(index) {
return (index + 4) % 4;
}
function getRow(index) {
return Math.floor(index / 4);
}
function render(field) {
return [...field]
.reduce((map, col, index) => {
if (getCol(index) === 0) {
map.push([ ]);
}
map[map.length - 1].push(col);
return map;
}, [ ])
.map(row => row
.map(col => col == null ? '*' : col)
.join('|'))
.join('\n');
}
function isFits(x) {
return x > 0 && x < 4;
}
function isBusy(field, position) {
return field[position] != null;
}
function moveUp(field) {
const map = [ ...field ];
for (let index = 0; index < map.length; index++) {
if (map[index] == null) {
continue;
}
let pos = index + 0;
let col = getCol(pos);
let row = getRow(pos);
while(isFits(row)) {
pos -= 4;
row = getRow(pos);
}
if (pos !== index) {
if (map[pos] === map[index]) {
map[pos] = map[index] * 2;
} else if (isBusy(map[pos])) {
} else {
map[pos] = map[index];
}
map[index] = null;
}
}
return map;
}
const map = create(`
*|*|*|*
*|*|*|4
*|*|*|*
*|*|*|2
`);
console.log(render(map));
console.log(render(moveUp(map)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment