来点学术的,求PI值动画
import javafx.animation.KeyFrame import javafx.animation.Timeline import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.geometry.Pos import javafx.scene.paint.Color import javafx.scene.shape.Circle import tornadofx.* class MyApp : App(蒙特卡洛算法求Pi::class) class 蒙特卡洛算法求Pi : View("learn 蒙特卡洛算法") { // 动画计时器 val result = stringProperty() val numPoint = intProperty() val Msg = stringProperty() val numPointInCircle = intProperty() var pause = true lateinit var circle0: Circle override val root = borderpane { val eventHandler = EventHandler<ActionEvent> { val p = point((0..600).random().toDouble(), (0..600).random().toDouble()) val c = Circle(p.x, p.y, 1.0) // 判断圆circle0是否包含点p,方法2 if (circle0.contains(p)) { c.fill = Color.RED numPointInCircle.value++ } center.add(c) numPoint.value++ val piEstimate = 4.0 * numPointInCircle.value / numPoint.value Msg.value = "总点数:${numPoint.value} -- 圆内点数:${numPointInCircle.value} -- Pi估计值: ${piEstimate} " } //动画 val animation = Timeline(KeyFrame(1.millis, eventHandler)) //速度 animation.cycleCount = 300000 //次数 // animation.play() top = vbox(5) { label(result) { isWrapText = true } label(Msg) hbox(5) { alignment = Pos.CENTER button("run"){ setPrefSize(200.0,50.0) action { if (!pause) { animation.pause() text = "run" pause = true } else { text = "pause" animation.play() pause = false } } } } } center = group { rectangle(0, 0, 600, 600) { fill = Color.YELLOW } circle0 = circle(300, 300, 300) { fill = Color.AZURE } prefHeight = 800.0 prefWidth = 800.0 } } }