import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import kotlin.concurrent.thread
import kotlin.random.Random
class FlappyBirdGame @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback {
private val birdPaint = Paint()
private val obstaclePaint = Paint()
private var birdY = 0f
private var birdSpeed = 0f
private var birdFlap = -30f
private var obstacleX = 0f
private var gapHeight = 400f
private var score = 0
init {
holder.addCallback(this)
birdPaint.color = Color.RED
obstaclePaint.color = Color.GREEN
}
override fun surfaceCreated(holder: SurfaceHolder) {
thread {
while (true) {
update()
draw()
Thread.sleep(16)
}
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
// Ничего не делаем
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
// Освобождаем ресурсы
}
private fun update() {
// Обновляем позицию птички и препятствий
birdSpeed += 1.5f
birdY += birdSpeed
obstacleX -= 8f
if (obstacleX < -300) {
obstacleX = width.toFloat()
gapHeight = Random.nextInt(200, 500).toFloat()
score++
}
// Проверяем столкновение птички с препятствием
if (birdY < 0 || birdY > height || (birdY < gapHeight - 200 || birdY > gapHeight + 200)
) {
// Птичка столкнулась с препятствием, сбрасываем игру
birdY = height / 2f
birdSpeed = 0f
obstacleX = width.toFloat()
gapHeight = Random.nextInt(200, 500).toFloat()
score = 0
}
}
private fun draw() {
val canvas = holder.lockCanvas()
canvas.drawColor(Color.BLACK)
// Рисуем птичку
canvas.drawCircle(200f, birdY, 50f, birdPaint)
// Рисуем препятствия
canvas.drawRect(obstacleX, 0f, obstacleX + 200f, gapHeight - 200f, obstaclePaint)
canvas.drawRect(obstacleX, gapHeight + 200f, obstacleX + 200f, height.toFloat(), obstaclePaint)
// Рисуем счет
val scoreText = "Score: $score"
canvas.drawText(scoreText, 50f, 100f, birdPaint)
holder.unlockCanvasAndPost(canvas)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
birdSpeed = birdFlap
}
return true
}
}