Skip to content

Instantly share code, notes, and snippets.

@alex-s168
Created March 29, 2024 21:14
Show Gist options
  • Save alex-s168/184d6962cc65572cf21a03d7ea4ec4df to your computer and use it in GitHub Desktop.
Save alex-s168/184d6962cc65572cf21a03d7ea4ec4df to your computer and use it in GitHub Desktop.
TicTacToe using Blitz.kt
import blitz.collections.Matrix
import blitz.collections.findCommon
import blitz.str.BoxDrawingCharSet
import blitz.str.ColoredChar
import blitz.str.MutMultiColoredMultiLineString
import blitz.term.Terminal
enum class State {
NONE,
A,
B
}
fun main() {
val matrix = Matrix(3, 3) { _, _ -> State.NONE }
fun prettyPrintMatrix() {
val text = MutMultiColoredMultiLineString(fill = ColoredChar(' '))
text.box(0 to 0, 8 to 4, BoxDrawingCharSet.NORMAL, Terminal.COLORS.WHITE.brighter.fg)
matrix.rows.forEachIndexed { row, line ->
line.forEachIndexed { col, state ->
text[row + 1, col * 2 + 2] = when (state) {
State.A -> ColoredChar('X', Terminal.COLORS.GREEN.brighter.fg )
State.B -> ColoredChar('O', Terminal.COLORS.RED.brighter.fg)
State.NONE -> ColoredChar(' ')
}
}
}
println(text)
}
fun isGameOver(): Boolean {
fun check(list: List<List<State>>): State? {
return list.map { it.findCommon() }.firstOrNull { it != State.NONE }
}
val winner = check(matrix.rows)
?: check(matrix.transposeCopy().rows)
?: check(matrix.diagonals())
?: if (matrix.rows.flatten().none { it == State.NONE }) State.NONE else null
when (winner) {
State.A -> println("You won!")
State.B -> println("Opponent won!")
State.NONE -> println("Draw!")
null -> return false
}
prettyPrintMatrix()
return true
}
while (true) {
// Player
print("Place: (x y) ")
val (x, y) = readln()
.trim()
.split(" ")
.map { it.toInt() - 1 }
if (matrix[x, y] != State.NONE) {
println("Field already in use!")
continue
}
matrix[x, y] = State.A
if (isGameOver())
break
// Bot
val (index, _) = matrix.rows
.flatten()
.withIndex()
.filter { (_, v) -> v == State.NONE }
.random()
matrix[index % 3, index / 3] = State.B
if (isGameOver())
break
prettyPrintMatrix()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment