lifehash
Version:
TypeScript/JavaScript implementation of LifeHash, a visual hash algorithm
75 lines (74 loc) • 2.31 kB
JavaScript
import { BitAggregator } from './BitAggregator.js';
import { BitEnumerator } from './BitEnumerator.js';
import { Grid } from './Grid.js';
import { Point } from './Point.js';
import { Colors } from './constants.js';
export class CellGrid extends Grid {
constructor(size) {
super(size);
this.data = new BitAggregator();
}
get_data() {
const aggregator = new BitAggregator();
for (const point of this.get_points()) {
aggregator.append(this.get_value(point));
}
return aggregator.get_data();
}
set_data(input) {
const e = new BitEnumerator(input);
let i = 0;
while (e.has_next()) {
this._storage[i] = e.next();
i += 1;
}
}
static is_alive_in_next_generation(current_alive, neighbors_count) {
if (current_alive) {
return [2, 3].includes(neighbors_count);
}
else {
return neighbors_count === 3;
}
}
count_neighbors(point) {
let total = 0;
for (const pointp of this.get_neighborhood(point)) {
if (pointp[0].equals(new Point(0, 0))) {
continue;
}
if (this.get_value(pointp[1])) {
total += 1;
}
}
return total;
}
next_generation(current_change_grid, next_cell_grid, next_change_grid) {
next_cell_grid.set_all(false);
next_change_grid.set_all(false);
for (const p of this.get_points()) {
const current_alive = this.get_value(p);
if (current_change_grid.get_value(p)) {
const neighbors_count = this.count_neighbors(p);
const next_alive = CellGrid.is_alive_in_next_generation(current_alive, neighbors_count);
if (next_alive) {
next_cell_grid.set_value(true, p);
}
if (current_alive !== next_alive) {
next_change_grid.set_changed(p);
}
}
else {
next_cell_grid.set_value(current_alive, p);
}
}
}
color_for_value(val) {
if (val) {
return Colors.white;
}
else {
return Colors.black;
}
}
}