commonMain.ru.casperix.math.array.Map2D.kt Maven / Gradle / Ivy
package ru.casperix.math.array
import ru.casperix.math.vector.int32.Vector2i
interface Map2D : Collection {
val dimension: Vector2i
fun get(position: Vector2i): Cell
val sizeX: Int get() = dimension.x
val sizeY: Int get() = dimension.y
fun isOutside(position: Vector2i): Boolean {
return !position.greaterOrEq(Vector2i.ZERO) || !position.less(dimension.toVector2i())
}
fun isInside(position: Vector2i): Boolean {
return position.greaterOrEq(Vector2i.ZERO) && position.less(dimension.toVector2i())
}
fun isBorder(position: Vector2i): Boolean {
return isBorder(position.x, position.y)
}
fun isBorder(x:Int, y:Int): Boolean {
if ((x == 0 || x == sizeX - 1) && (y >= 0 && y <= sizeY - 1)) {
return true
}
if ((y == 0 || y == sizeY - 1) && (x >= 0 && x <= sizeX - 1)) {
return true
}
return false
}
fun get(x:Int, y:Int): Cell {
return get(Vector2i(x, y))
}
fun getOrNull(position: Vector2i): Cell? {
if (isOutside(position)) return null
return get(position)
}
fun iterate(op: (Int, Int, Cell) -> Unit) {
for (x in 0 until dimension.x) {
for (y in 0 until dimension.y) {
val value = get(x, y)
op(x, y, value)
}
}
}
private fun first(op: (Cell) -> Boolean): Boolean {
for (x in 0 until dimension.x) {
for (y in 0 until dimension.y) {
if (op(get(x, y))) {
return true
}
}
}
return false
}
private fun last(op: (Cell) -> Boolean): Boolean {
for (x in dimension.x - 1 downTo 0) {
for (y in dimension.y - 1 downTo 0) {
if (op(get(x, y))) {
return true
}
}
}
return false
}
override val size: Int
get() = dimension.volume()
override fun contains(element: Cell): Boolean {
return first {
it == element
}
}
override fun containsAll(elements: Collection): Boolean {
return toList().containsAll(elements)
}
override fun isEmpty(): Boolean {
return size == 0
}
override fun iterator(): Iterator {
return toList().iterator()
}
fun toList(): List {
val list = mutableListOf()
first {
list.add(it)
false
}
return list
}
} | | | | |