Android水果机实现代码
时间: 2024-01-08 19:39:01 浏览: 32
以下是一个简单的Android水果机实现代码的示例:
```java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private ImageView imgSlot1, imgSlot2, imgSlot3;
private TextView txtResult;
private Button btnSpin;
private int[] fruits = {R.drawable.apple, R.drawable.banana, R.drawable.orange};
private Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgSlot1 = findViewById(R.id.img_slot1);
imgSlot2 = findViewById(R.id.img_slot2);
imgSlot3 = findViewById(R.id.img_slot3);
txtResult = findViewById(R.id.txt_result);
btnSpin = findViewById(R.id.btn_spin);
btnSpin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spin();
}
});
}
private void spin() {
int randomFruit1 = random.nextInt(fruits.length);
int randomFruit2 = random.nextInt(fruits.length);
int randomFruit3 = random.nextInt(fruits.length);
imgSlot1.setImageResource(fruits[randomFruit1]);
imgSlot2.setImageResource(fruits[randomFruit2]);
imgSlot3.setImageResource(fruits[randomFruit3]);
if (randomFruit1 == randomFruit2 && randomFruit2 == randomFruit3) {
txtResult.setText("Congratulations! You won!");
} else {
txtResult.setText("Try again!");
}
}
}
```
这个示例代码中,使用了ImageView来显示水果的图片,TextView用来显示结果,Button用来触发旋转操作。在`spin()`方法中,通过随机数生成器来生成三个随机的水果图片,并将其显示在ImageView上。如果三个图片相同,则显示"Congratulations! You won!",否则显示"Try again!"。
请注意,这只是一个简单示例,实际的水果机可能需要更复杂的逻辑和动画效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)