我试图将csv文件中的一些项目添加到画布视图中。我正在制作一个游戏,你可以在这里挖掘"一个洞,并得到一些战利品。像扫雷类型的游戏。但我不确定如何在画布上随机添加项目。我所有的项目都在arraylist,但不知道如何在游戏中添加它们。然后在找到战利品时更新我的分数。
我的代码:
// List of items from CSV file.
private ArrayList<ItemObject> mLoot;
private String itemSize;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// Let the view know that we want to draw.
setWillNotDraw(false);
getHolder().addCallback(this);
Resources res = getResources();
// background image
mBackground = BitmapFactory.decodeResource(res, R.drawable.field);
mBlackPaint = new Paint();
// Score text
mScoreTextPaint = new Paint();
mScoreTextPaint.setColor(Color.WHITE);
mScoreTextPaint.setTextSize(60.0f);
mScoreTextPaint.setTextAlign(Paint.Align.CENTER);
// Show hole image
mHole = BitmapFactory.decodeResource(res, R.drawable.hole);
mPoints = new ArrayList<>();
// Get CSV items
InputStream inputStream = getResources().openRawResource(R.raw.items);
GetCSVFile csvFile = new GetCSVFile(inputStream);
mLoot = csvFile.read();
itemSize = String.valueOf(mLoot.size());
for(ItemObject itemData:mLoot ) {
//TODO: add a random x,y position for loot?
// itemData.getLoot() - "gold"
// itemData.getValue() - "50"
}
我的onDraw方法:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Clear the canvas by drawing a single color.
canvas.drawColor(Color.BLACK);
// Draw image to cover all dimensions of the screen.
canvas.drawBitmap(mBackground, null, mDimensions, mBlackPaint);
// Draw a circle at each touch.
for(Point p: mPoints){
// show hole's image when a player touches the screen
canvas.drawBitmap(mHole,p.x,p.y,null);
}
// Draw text in middle of screen.
canvas.drawText("Hidden Treasure: " + itemSize,
mDimensions.width() / 2.0f,
mDimensions.height() / 15.0f,
mScoreTextPaint);
} // end onDraw
答案 0 :(得分:1)
如果您使用的是整个屏幕,请获取屏幕宽度和高度:
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int maxHeight = displayMetrics.heightPixels;
int maxWidth = displayMetrics.widthPixels;
否则确定您需要的maxX和maxY值。
创建一个小方法来获得随机位置;
private int randomPosition(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
在你的&#34; ItemObject&#34;你应该为对象坐标添加setter和getter:
String item = "";
int x = 0;
int y = 0;
public void setItem(String item) { this.item = item; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public String getItem() { return this.item; }
public int getX() { return this.x; }
public int getY() { return this.y; }
将csv文件的内容作为字符串获取后,您可以在分隔符上调用分割:
String myDelimiter = ","; // Or what ever your delimiter is
String[] lines = csvData.Split(myDelimiter);
现在循环直线并获得随机位置;
for(String s : lines ) {
// if 0 is the smallest x coordinates
int x = random(0, maxWidth);
int y = random(0, maxHeight);
ItemObject item = new ItemObject();
item.setItem(s)
item.setX(x);
item.setY(y);
mLoot.add(item);
}
在您的绘图程序中,只需使用步骤&#34; mLoot&#34;并绘制对象。