Created
December 11, 2020 07:26
-
-
Save mmacphail/e67331f3a5f7109ac23bdb567464fb94 to your computer and use it in GitHub Desktop.
tress.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package eu.macphail | |
sealed class PartOfTree | |
data class Leaf(val sprite: String = "Leaf") : PartOfTree() | |
data class Flower(val sprite: String = "Flower") : PartOfTree() | |
data class Branch(val subParts: List<PartOfTree>, | |
val enterBranch: String = "Enter Branch", | |
val exitBranch: String = "Exit Branch") : PartOfTree() | |
data class Painting(val sprites: String = "") { | |
fun add(sprite: String) = if(sprites.isBlank()) { | |
Painting(sprite) | |
} else { | |
Painting("$sprites,$sprite") | |
} | |
} | |
fun makeBranch(vararg parts: PartOfTree) = Branch(parts.toList()) | |
fun main() { | |
val parts = listOf(makeBranch(Leaf(), Flower(), Flower(), | |
makeBranch(Flower(), Leaf(), Leaf()), | |
makeBranch(Flower(), Flower(), Flower())), | |
makeBranch(Flower(), Leaf(), Leaf()), | |
makeBranch(Leaf(), Leaf(), Flower()), | |
makeBranch(Flower(), Leaf(), Flower())) | |
println(paintTree(parts).sprites) | |
} | |
private fun paintTree(parts: List<PartOfTree>, existingPainting: Painting = Painting()): Painting { | |
return parts.fold(existingPainting) { painting, part -> | |
when (part) { | |
is Leaf -> painting.add(part.sprite) | |
is Flower -> painting.add(part.sprite) | |
is Branch -> | |
painting.add(part.enterBranch) | |
.add(paintTree(part.subParts).sprites) | |
.add(part.exitBranch) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment