1
Fork 0

typescript(loopover): feat: added a basic GameState class

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-11-25 09:56:09 +02:00 committed by prescientmoon
parent 91e8f869aa
commit 6894448f60
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
6 changed files with 64 additions and 1 deletions
typescript/loopover/src

View file

@ -0,0 +1,45 @@
import { assert } from '@thi.ng/api'
import { List } from 'immutable'
import { Direction } from '../types/direction'
import { rangeArray } from '../helpers/rangeArray'
export class GameState {
public height: number
public constructor(public cells: List<number>, public width: number) {
const height = cells.count() / width
assert(
height === Math.floor(height),
`Recived non-integer height: ${height}`
)
this.height = height
}
public moveX(direction: Direction, layers: Iterable<number>) {
const newState = this.cells.withMutations(list => {
for (const layer of layers) {
const slice = list.slice(
layer * this.width,
(layer + 1) * this.width
)
if (direction === -1) {
const first = slice.first<number>()
slice.shift()
slice.push(first)
} else if (direction === 1) {
const last = slice.last<number>()
slice.unshift(last)
}
for (let i = 0; i < slice.count(); i++) {
list[i + layer * this.width] = slice[i]
}
}
})
return new GameState(newState, this.width)
}
}

View file

@ -0,0 +1,6 @@
import { rangeArray } from './rangeArray'
export const chunkX = <T>(arr: T[], width: number, height: number): T[][] =>
rangeArray(0, this.height).map(index =>
arr.slice(index * height, (index + 1) * width)
)

View file

@ -0,0 +1,4 @@
export const rangeArray = (start: number, end: number) =>
Array(end - start)
.fill(true)
.map((_, i) => i + start)

View file

@ -0,0 +1 @@
export type Direction = -1 | 1