typescript(loopover): feat: added a basic GameState class
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
91e8f869aa
commit
6894448f60
6 changed files with 64 additions and 1 deletions
typescript/loopover/src
45
typescript/loopover/src/classes/Game.ts
Normal file
45
typescript/loopover/src/classes/Game.ts
Normal 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)
|
||||
}
|
||||
}
|
6
typescript/loopover/src/helpers/chunkX.ts
Normal file
6
typescript/loopover/src/helpers/chunkX.ts
Normal 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)
|
||||
)
|
4
typescript/loopover/src/helpers/rangeArray.ts
Normal file
4
typescript/loopover/src/helpers/rangeArray.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
export const rangeArray = (start: number, end: number) =>
|
||||
Array(end - start)
|
||||
.fill(true)
|
||||
.map((_, i) => i + start)
|
1
typescript/loopover/src/types/direction.ts
Normal file
1
typescript/loopover/src/types/direction.ts
Normal file
|
@ -0,0 +1 @@
|
|||
export type Direction = -1 | 1
|
Loading…
Add table
Add a link
Reference in a new issue