Skip to content

Instantly share code, notes, and snippets.

@occar421
Created January 9, 2016 13:58
Show Gist options
  • Save occar421/4e822784bcbb7255c882 to your computer and use it in GitHub Desktop.
Save occar421/4e822784bcbb7255c882 to your computer and use it in GitHub Desktop.
NetLogo like processing on Kotlin 2nd version (needs kotlin-reflect.kt)
fun main(args: Array<String>) {
setup()
}
inline fun <reified T : Agent> ask(noinline job: T.() -> Unit): Unit {
for (t in AgentsManager.getAgent<T>()) {
job(t)
}
}
inline fun <reified T : Agent> create(num: Int, init: T.() -> Unit): Unit {
AgentsManager.AgentMap.plusAssign(T::class.qualifiedName!!, Array(num, {
var t = T::class.constructors.first().call(AgentsManager.counter, "", Shapes.Turtle, 0.0, 0.0)
init(t)
AgentsManager.counter += 1
t
}).toList())
}
fun setup() {
create<Agent>(5) {
shape = Shapes.Circle
}
create<Agent>(2) {
shape = Shapes.Turtle
}
ask<Agent> {
println(who)
}
ask<Agent> {
who += 10
label = who.toString()
}
ask<Agent>() {
println("$who ; $label @ $shape")
}
}
object AgentsManager {
object AgentMap {
val map = mapOf<String, List<Any>>().toLinkedMap()
inline fun <reified T> get(classQualifiedName: String): List<T> {
val array = map[classQualifiedName]
return if (array != null) {
array.map { it as T }
} else {
emptyList()
}
}
fun <T> plus(classQualifiedName: String, newList: List<T>): List<T> {
val old = map[classQualifiedName]
return if (old != null) {
old.map { it as T } + newList
} else {
newList
}
}
fun <T> plusAssign(classQualifiedName: String, newList: List<T>) {
map[classQualifiedName] = plus(classQualifiedName, newList).map { it as Any }
}
}
inline fun <reified T> getAgent() = AgentMap.get<T>(T::class.qualifiedName!!)
var counter: Int = 0
}
open class Agent(var who: Int,
var label: String,
var shape: Shapes,
var x: Double,
var y: Double) {
}
enum class Shapes {
Turtle,
Circle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment