напиши код на kotlin для игры змейка
Условие:
Решение:
Конечно! Вот пример кода на Kotlin для игры "Змейка":
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.application.Application
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.canvas.Canvas
import javafx.scene.canvas.GraphicsContext
import javafx.scene.input.KeyCode
import javafx.scene.paint.Color
import javafx.stage.Stage
import javafx.util.Duration
import java.util.*
class SnakeGame : Application() {
private val canvasWidth = 400.0
private val canvasHeight = 400.0
private val gridSize = 20.0
private val initialSnakeLength = 3
private var snakeX = 0
private var snakeY = 0
private var snakeLength = initialSnakeLength
private var direction = Direction.RIGHT
private var gameOver = false
private val snakeBody = LinkedList<Pair<Int, Int>>()
private var foodX = 0
private var foodY = 0
override fun start(primaryStage: Stage) {
val root = Group()
val canvas = Canvas(canvasWidth, canvasHeight)
val gc = canvas.graphicsContext2D
root.children.add(canvas)
generateFood()
val gameLoop = Timeline()
gameLoop.keyFrames.add(KeyFrame(Duration.seconds(0.1), {
if (!gameOver) {
update()
draw(gc)
}
}))
gameLoop.cycleCount = Timeline.INDEFINITE
primaryStage.title = "Snake Game"
primaryStage.scene = Scene(root)
primaryStage.scene.setOnKeyPressed { event ->
when (event.code) {
KeyCode.UP -> direction = Direction.UP
KeyCode.DOWN -> direction = Direction.DOWN
KeyCode.LEFT -> direction = Direction.LEFT
KeyCode.RIGHT -> direction = Direction.RIGHT
}
}
gameLoop.play()
...


