打地鼠游戏android studio
时间: 2023-12-20 19:32:23 浏览: 148
android打地鼠游戏
5星 · 资源好评率100%
根据提供的引用内容,以下是一个使用Android Studio实现打地鼠游戏的示例代码:
```java
// MainActivity.java
package com.example.playmouse;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ImageButton[] holes;
private TextView scoreText;
private int score;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
holes = new ImageButton[4];
holes[0] = findViewById(R.id.hole1);
holes[1] = findViewById(R.id.hole2);
holes[2] = findViewById(R.id.hole3);
holes[3] = findViewById(R.id.hole4);
scoreText = findViewById(R.id.scoreText);
score = 0;
for (int i = 0; i < holes.length; i++) {
final int index = i;
holes[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holes[index].isEnabled()) {
score++;
scoreText.setText("Score: " + score);
holes[index].setEnabled(false);
holes[index].setImageResource(R.drawable.hit_mole);
}
}
});
}
}
}
```
```xml
<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score: 0"
android:textSize="24sp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="@+id/hole1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/mole"
android:background="@android:color/transparent" />
<ImageButton
android:id="@+id/hole2"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/mole"
android:background="@android:color/transparent" />
<ImageButton
android:id="@+id/hole3"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/mole"
android:background="@android:color/transparent" />
<ImageButton
android:id="@+id/hole4"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/mole"
android:background="@android:color/transparent" />
</LinearLayout>
</LinearLayout>
```
请注意,上述代码仅为示例,需要根据实际需求进行适当修改和完善。此示例使用LinearLayout作为布局容器,包含一个TextView用于显示分数,以及四个ImageButton用于表示地洞。点击地洞时,分数会增加,并且对应的ImageButton会显示打中地鼠的效果图。
阅读全文