import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

lateinit var diceImage: ImageView

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.Roll_Button)
rollButton.text = "Let's Roll"
rollButton.setOnClickListener{
rollDice()
}

diceImage = findViewById(R.id.dice_Image)
}

private fun rollDice() {
val dice = Dice(6)
val diceroll = dice.roll()

// val randomInt = Random().nextInt(6) + 1
val drawableResource = when (rollDice) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}

diceImage.setImageResource(drawableResource)
}
}

class Dice(val numSides: Int) {
fun roll(): Int {
return(1..numSides).random()
}
}
My code 
compare to
Udacity code
package com.example.android.diceroller
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
lateinit var diceImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.setOnClickListener {
rollDice()
}
diceImage = findViewById(R.id.dice_image)
}
private fun rollDice() {
val randomInt = Random().nextInt(6) + 1
val drawableResource = when (randomInt) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
diceImage.setImageResource(drawableResource)
}
}


0 Comments

Brand creation, trend analysis & style consulting

Lorem Ipsum has been the industry's standard dummy text ever since. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.