我目前所拥有的是一款游戏,用户按下精灵,当按下它时,它将添加到他们的分数中,然后将其添加到分数中,以便精灵消失。我遇到的问题是,在将精灵从数组列表中完全删除时,一旦按下它们,我将无法弄清楚如何使其重新出现,我是将它们读取到数组列表中还是将其放在不同的方法?
这是精灵代码:
package cct.mad.lab;
import java.util.Random;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Vibrator;
public class Sprite {
//x,y position of sprite - initial position (0,50)
private GameView gameView;
private Bitmap spritebmp;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
private Random random = new Random();
private int x = random.nextInt(200)-1;
private int y = random.nextInt(200)-1;
int xSpeed = (random.nextInt(30)-15);
int ySpeed = (random.nextInt(30)-15);
public Sprite(GameView gameView) {
this.gameView=gameView;
spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
R.drawable.spritehead);
this.bmp_width = spritebmp.getWidth();
this.bmp_height= spritebmp.getHeight();
//random y coordinate for sprite spawn
x = gameView.getWidth();
x = random.nextInt(x);
y = gameView.getHeight();
y = random.nextInt(y);
}
//update the position of the sprite
public void update() {
x = x + xSpeed;
y = y + ySpeed;
wrapAround(); //Adjust motion of sprite.
}
public void draw(Canvas canvas) {
//Draw sprite image
canvas.drawBitmap(spritebmp, x , y, null);
}
//y -= gameView.getHeight();//Reset y
public void wrapAround(){
//Code to wrap around
//increment x whilst not off screen
if (x >= (gameView.getWidth() - 40)){ //if gone off the right sides of screen
xSpeed = (xSpeed * -1);
}
if (x <= -10)
{
xSpeed = (xSpeed * -1);
}
if (y >= (gameView.getHeight() - 40)){//if gone off the bottom of screen
ySpeed = (ySpeed * -1);
}
if (y <= 0)//if gone off the top of the screen
{
ySpeed = (ySpeed * -1);
}
xSpeed = (xSpeed * -1);
}
/* Checks if the Sprite was touched. */
public boolean wasItTouched(float ex, float ey) {
boolean touched = false;
if ((x <= ex) && (ex < x + bmp_width) &&
(y <= ey) && (ey < y + bmp_height)) {
touched = true;
}
return touched;
}//End of wasItTouched
}
这是我的代码,用于实际显示项目和数组列表:
public void surfaceCreated(SurfaceHolder holder) {
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
for (int sp =0; spritesArrayList.size() < spNumber; sp++) {
spritesArrayList.add(sprite = new Sprite(this));
}
}
我不确定为什么它不起作用
最佳答案
当我必须从对象添加/删除项目时,通常我使用HashMap
。
在您的情况下,类似于HashMap<String,Sprite>
,因此您可以通过哈希键添加/删除标识它们的项目。
例如
//HashMap<String,Sprite> hashSprite
//add
hashSprite.put("sprite1",new Sprite(this));
//remove
hashSprite.remove("sprite1")
我知道这不是一个真正的答案,但是建议还是值得赞赏的!
关于java - 清空后重新填充数组列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30254799/