Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package board
- import board.Direction.*
- import java.lang.IllegalArgumentException
- fun createSquareBoard(width: Int): SquareBoard = object : SquareBoard {
- override val width: Int
- get() = width
- val cells = mutableListOf<Cell>()
- init {
- for (i in 1..width)
- for (j in 1..width)
- cells.add(Cell(i, j))
- }
- fun ijToInt(i: Int, j: Int) = i * width - (width - j)
- override fun getCellOrNull(i: Int, j: Int): Cell? =
- if (i !in 1..width || j !in 1..width) null
- else getCell(i, j)
- override fun getCell(i: Int, j: Int): Cell =
- if (i !in 1..width || j !in 1..width) throw IllegalArgumentException()
- else cells[ijToInt(i, j) - 1]
- override fun getAllCells(): Collection<Cell> = cells
- override fun getRow(i: Int, jRange: IntProgression): List<Cell> {
- val rows = mutableListOf<Cell>()
- for (j in jRange)
- getCellOrNull(i, j)?.let { rows.add(it) }
- return rows
- }
- override fun getColumn(iRange: IntProgression, j: Int): List<Cell> {
- val cols = mutableListOf<Cell>()
- for (i in iRange)
- getCellOrNull(i, j)?.let { cols.add(it) }
- return cols
- }
- override fun Cell.getNeighbour(direction: Direction): Cell? {
- return when (direction) {
- DOWN -> getCellOrNull(i + 1, j)
- UP -> getCellOrNull(i - 1, j)
- LEFT -> getCellOrNull(i, j - 1)
- RIGHT -> getCellOrNull(i, j + 1)
- }
- }
- }
- fun <T> createGameBoard(width: Int): GameBoard<T> = object : GameBoard<T>, SquareBoard by createSquareBoard(width) {
- val cells = getAllCells().toList()
- val cellsValues = mutableMapOf<Cell, T?>()
- init {
- for (cell in cells)
- cellsValues[cell] = null // we want to store null reference as default values
- }
- override fun get(cell: Cell): T? {
- return cellsValues[cell]
- }
- override fun set(cell: Cell, value: T?) {
- cellsValues[cell] = value
- }
- override fun filter(predicate: (T?) -> Boolean): Collection<Cell> =
- cellsValues.filter { predicate(it.value) }.keys
- override fun find(predicate: (T?) -> Boolean): Cell? =
- filter { predicate(it) }.firstOrNull()
- override fun any(predicate: (T?) -> Boolean): Boolean =
- cellsValues.filter { predicate(it.value) }.isNotEmpty()
- override fun all(predicate: (T?) -> Boolean): Boolean =
- filter { predicate(it) }.size == cells.size
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement