vendredi 23 avril 2021

Is the random function in Kotlin slow?

I was using the random function to make a dice app in Kotlin. I also added a button to roll the dice and a Toast to notify that the dice are rolled. But, if I keep on pressing the roll button repeatedly, the app seems to skip some button clicks. Also, the Toast is showing absurd behaviour, it doesn't refresh on some clicks. I think that this could be due to the slow random function where I press the roll button even before the roll has been executed. Could anyone please confirm.

Here's my MainActivity.kt:

  package com.example.diceroller

  import android.os.Bundle
  import android.widget.Button
  import android.widget.TextView
  import android.widget.Toast
  import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toast = Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT )

    val rollButton: Button = findViewById(R.id.button)
    rollButton.setOnClickListener {
        toast.cancel()
        toast.show()
        rollDice()
    }
}

private fun rollDice() {
    val dice = Dice(6)
    val diceRoll = dice.roll()
    val resultTextView: TextView = findViewById(R.id.textView)
    resultTextView.text = diceRoll.toString()
 }
}

class Dice(private val numSides: Int) {
fun roll(): Int {
    return (1..numSides).random()
 }
}



Aucun commentaire:

Enregistrer un commentaire