分錢問題:
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
import javafx.animation.AnimationTimer
import javafx.collections.FXCollections
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.util.Duration
import tornadofx.*
class LearnApp : App(LearnV::class)
class LearnV : View("learn 分錢問題") {
// 每一個矩形寬度
val w = 10.0
// 100個矩形容器
val rec = FXCollections.observableArrayList<Rectangle>()
val b = (0..99)
// 100我的,每人100元
val money = b.map { 100 }.toIntArray()
// 動畫計時器
val aniTimer=AniTimer(this)
// 每次給其餘人10元
val money1=10
val result= stringProperty()
override val root = vbox(5) {
label(result){
isWrapText=true
}
hbox(5) {
button("run").action {
// ani()
aniTimer.start()
}
button("stop").action {
// ani()
aniTimer.stop()
}
}
hbox(5) {
// 畫100個寬度爲w,高度爲100的矩形,方法1
// var i = 0
// b.forEach {
// val r = rectangle(w * it, 0.0, w, 100.0) {
// fill = Color.BLUE
// }
// rec.add(r)
// i.inc()
// }
// 畫100個寬度爲w,高度爲100的矩形,方法2
for(i in money.indices){
val r = rectangle(w * i, 0.0, w, 100.0) {
fill = Color.BLUE
}
rec.add(r)
}
}
prefWidth = 800.0
prefHeight = 800.0
}
// 此方法沒法中止動畫
fun ani() {
class AniTimer : AnimationTimer() {
var lastTime = 0L
override fun handle(now: Long) {
if ((now - lastTime) > 10000000) {
lastTime = now
} else {
return
}
paint()
}
}
AniTimer().start()
}
fun paint() {
// 999次後的結果
// (0..999).forEach {
// var i = 0
// timeline {
// keyframe(Duration.seconds(0.10)) {
// money.forEach {
// val j = b.random()
// if(money[i]>0){
// money[i] -= 10
// money[j] += 10
// keyvalue(rec[i].heightProperty(), money[i])
// keyvalue(rec[j].heightProperty(), money[j])
// }
// i++
// }
// println(money.toList())
// }
// }
// }
var i=0
timeline {
keyframe(Duration.seconds(0.10)) {
money.forEach {
val j = b.random()
if(money[i]>0){
money[i] -= money1
money[j] += money1
keyvalue(rec[i].heightProperty(), money[i])
keyvalue(rec[j].heightProperty(), money[j])
}
i++
}
// 如要看排序後的結果,取消下面註釋
// money.sort()
result.value=money.toList().toString()
// println(money.toList())
}
}
}
// 此方法能夠中止動畫
class AniTimer(val learnV:LearnV) : AnimationTimer() {
var lastTime = 0L
override fun handle(now: Long) {
if ((now - lastTime) > 10000000) {
lastTime = now
} else {
return
}
learnV.paint()
}
}
}