用android studio做一个打地鼠小游戏
时间: 2023-12-03 09:05:55 浏览: 184
基于Android Studio制作的一款打地鼠小游戏
以下是使用Android Studio实现打地鼠小游戏的步骤:
1.创建一个新的Android Studio项目,选择Empty Activity模板。
2.在app/build.gradle文件中添加以下依赖项:
```gradle
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
```
3.在activity_main.xml文件中添加一个RelativeLayout布局,并在其中添加一个ImageView元素,用于显示地鼠图片。
4.创建一个名为Mouse的Java类,用于表示地鼠对象。该类应该包含以下属性:
```java
public class Mouse {
private int x;
private int y;
private boolean visible;
public Mouse(int x, int y) {
this.x = x;
this.y = y;
this.visible = false;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
```
5.在MainActivity.java文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mouseImageView;
private Mouse mouse;
private Handler handler;
private int score;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mouseImageView = findViewById(R.id.mouseImageView);
mouseImageView.setOnClickListener(this);
mouse = new Mouse(0, 0);
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
update();
handler.postDelayed(this, 1000);
}
}, 1000);
}
private void update() {
Random random = new Random();
int x = random.nextInt(mouseImageView.getWidth() - mouseImageView.getDrawable().getIntrinsicWidth());
int y = random.nextInt(mouseImageView.getHeight() - mouseImageView.getDrawable().getIntrinsicHeight());
mouse.setX(x);
mouse.setY(y);
mouse.setVisible(true);
mouseImageView.setX(x);
mouseImageView.setY(y);
mouseImageView.setVisibility(View.VISIBLE);
}
@Override
public void onClick(View v) {
if (mouse.isVisible()) {
score++;
Toast.makeText(this, "Score: " + score, Toast.LENGTH_SHORT).show();
mouse.setVisible(false);
mouseImageView.setVisibility(View.INVISIBLE);
}
}
}
```
6.运行应用程序,您应该能够看到一个ImageView元素,该元素将在屏幕上随机显示,并且当用户单击它时,将显示一个Toast消息,显示用户的得分。
阅读全文