Zum Inhalt springenmljr.eu— Michael Reinegger · Linz (AT)
KurzprofilKontakt
← mljr.eu / Werkkatalog

Game Of Life Multiplatform

Conways Game of Life als Kotlin-Multiplatform-Projekt für Desktop und Android. Als Universitäts-Programmierprojekt entwickelt, das KMPs gemeinsame Logik und plattformspezifische UI-Fähigkeiten erkundet.

Eine im Rahmen eines Uni-Programmierprojekts entstandene Implementierung von Conways Game of Life mit Kotlin Multiplatform, die die Simulationslogik — Gitterzustand, Generationsschritte, das Zellregelwerk — zwischen einem Desktop-Build und einer Android-App teilt, statt sie zweimal zu schreiben. Das Projekt existiert primär, um zu erkunden, wo die geteilte Codegrenze von KMP in der Praxis tatsächlich liegt: der zelluläre Automaten-Kern ist reines Kotlin ohne Plattformabhängigkeiten, während Rendering des Gitters und Eingabeverarbeitung plattformspezifische UI-Schichten darüber sind — eine kleine, aber konkrete Fallstudie dazu, was sich über Zielplattformen hinweg zu teilen lohnt und was nicht.

Architektur

graph TD
  Game["commonMain
Game.kt (pure Kotlin rules)"] --> Android["androidMain UI"] Game --> Desktop["desktopMain UI"] Timer["GameTimer"] -->|"onTick: step()"| Game Game -->|mutableStateOf per Cell| Android Game -->|mutableStateOf per Cell| Desktop

Unter der Haube

The cellular-automaton rules live once in commonMain and are shared verbatim by every platform target — only the rendering differs. Four rule variants (Conway 23/3, 3/3, 13/3, 34/3) are selectable at runtime.

composeApp/src/commonMain/kotlin/eu/mljr/Game.kt
Kotlin
when (rule) {
    0 -> { // Conway (23/3)
        if (p.isAlive() && (p.neighbors != 2 && p.neighbors != 3)) set(i, !c.state)
        else if (p.isDead() && p.neighbors == 3) set(i, !c.state)
    }
    1 -> { // 3/3
        if (p.isAlive() && p.neighbors != 3) set(i, !c.state)
        else if (p.isDead() && p.neighbors == 3) set(i, !c.state)
    }
    2 -> { // 13/3
        if (p.isAlive() && (p.neighbors != 1 && p.neighbors != 3)) set(i, !c.state)
        else if (p.isDead() && p.neighbors == 3) set(i, !c.state)
    }
    3 -> { // 34/3
        if (p.isAlive() && (p.neighbors != 4 && p.neighbors != 3)) set(i, !c.state)
        else if (p.isDead() && p.neighbors == 3) set(i, !c.state)
    }
    else -> throw IndexOutOfBoundsException("There exists no rule with index $rule")
}