-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercício A 4.2 - Adicional
87 lines (74 loc) · 3.05 KB
/
Exercício A 4.2 - Adicional
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.example.rolldice
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
/**
* This activity allows the user to roll a dice and view the result
* on the screen.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.button) //encontra o button
rollButton.setOnClickListener { //vai definir o que vai ser feito quando se tocar no button
rollDice() // colocar a lógica aqui na função
} //podes por tudo numa linha para condensar o codigo
}
/**
* Roll the dice and update the screen with the result.
*/
private fun rollDice() { //criar e lançar um dado e depois exibir o resultado na TextView.
// Create new Dice object with 6 sides and roll the dice
val dice = Dice(6) //dado com 6 lados
val dice2 = Dice(6)
val diceRoll = dice.roll()
val diceRoll2 = dice2.roll()
// Find the ImageView in the layout
val diceImage:ImageView = findViewById(R.id.imageView)
val diceImage2:ImageView = findViewById(R.id.imageView2)
when(diceRoll)
{
// Determine which drawable resource ID to use based on the dice roll
1 -> diceImage.setImageResource(R.drawable.dice_1)
2 -> diceImage.setImageResource(R.drawable.dice_2)
3 -> diceImage.setImageResource(R.drawable.dice_3)
4 -> diceImage.setImageResource(R.drawable.dice_4)
5 -> diceImage.setImageResource(R.drawable.dice_5)
6 -> diceImage.setImageResource(R.drawable.dice_6)
/*
*
* ou
* val drawableResource = when (diceRoll) {
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
6 -> R.drawable.dice_6
}
// Update the ImageView with the correct drawable resource ID
diceImage.setImageResource(drawableResource)
*
* // Update the content description
diceImage.contentDescription = diceRoll.toString()
* */
when(diceRoll2){
// Determine which drawable resource ID to use based on the dice roll
1 -> diceImage2.setImageResource(R.drawable.dice_1)
2 -> diceImage2.setImageResource(R.drawable.dice_2)
3 -> diceImage2.setImageResource(R.drawable.dice_3)
4 -> diceImage2.setImageResource(R.drawable.dice_4)
5 -> diceImage2.setImageResource(R.drawable.dice_5)
6 -> diceImage2.setImageResource(R.drawable.dice_6)
}
}
}
}
class Dice(val numSides: Int) {
//lógica para se lançar um dado
fun roll(): Int {
return (1..numSides).random()
}
}