android studio打地鼠游戏具体Java代码
时间: 2024-04-07 20:26:50 浏览: 72
基于AndroidStudio的打地鼠游戏设计源码
5星 · 资源好评率100%
当然,我可以给你介绍一下Android Studio打地鼠游戏的具体Java代码。下面是一个简单的示例代码:
```java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private Button[] buttons;
private TextView scoreTextView;
private int score;
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = new Button[9];
buttons[0] = findViewById(R.id.button1);
buttons[1] = findViewById(R.id.button2);
buttons[2] = findViewById(R.id.button3);
buttons[3] = findViewById(R.id.button4);
buttons[4] = findViewById(R.id.button5);
buttons[5] = findViewById(R.id.button6);
buttons[6] = findViewById(R.id.button7);
buttons[7] = findViewById(R.id.button8);
buttons[8] = findViewById(R.id.button9);
scoreTextView = findViewById(R.id.scoreTextView);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
hideMole();
showMole();
handler.postDelayed(this, 1000);
}
};
for (Button button : buttons) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getTag() != null && (int) v.getTag() == 1) {
score++;
scoreTextView.setText("Score: " + score);
}
}
});
}
}
@Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, 1000);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
private void hideMole() {
for (Button button : buttons) {
button.setText("");
button.setTag(0);
}
}
private void showMole() {
Random random = new Random();
int index = random.nextInt(9);
buttons[index].setText("Mole");
buttons[index].setTag(1);
}
}
```
这段代码实现了一个简单的打地鼠游戏。在布局文件中,有9个按钮用于显示地鼠,一个TextView用于显示得分。在MainActivity中,我们使用数组来存储按钮,并在onCreate方法中初始化这些按钮。我们还创建了一个Handler和一个Runnable,用于定时显示和隐藏地鼠。当用户点击按钮时,如果按钮的tag为1,则增加得分。
阅读全文