2014-01-22 24 views
1

我有一个应用程序,有一个正方形,每隔1.5秒在屏幕上移动,每次你点击它,你就得到一个点。我试图让它在你点击正方形的地方变成随机颜色。另外,我希望在每平方毫秒移动一次的较硬模式设置下有一个选项。Java Android应用程序随机颜色和计时器

这里是我的绘制方法:

protected void onDraw(Canvas canvas) { 
canvas.drawColor(Color.BLUE); 
Paint dotPaint = new Paint();  
    canvas.drawRect(dotX, dotY, dotX + 60, dotY + 60, dotPaint); 
dotPaint.setColor(Color.WHITE); 
dotPaint.setTextSize(60); 
    canvas.drawText("Score: " + score, 20, 60, dotPaint);           

,这里是我的onTouch方法:

public boolean onTouch(View v, MotionEvent event) { 
if (detectHit((int)event.getX(), (int)event.getY())) { 
    score++; 
    invalidate(); 
} 
     return false; 

我也不太清楚如何去让每一次点击的平方变化的颜色。

Also, here is my menu items: 

public boolean onOptionsItemSelected(MenuItem item) { 
    // handle menu item selection 
    switch (item.getItemId()){ 
     case R.id.item1: 
      newGame(); 
      return true; 
     case R.id.item2: 
      quit(); 
      return true; 
     case R.id.item3: 
      harder(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 

and my harder method: 
public void harder(){ 
    timer.schedule(task, 0, 700); 
} 
+0

所以,我想我涵盖了大部分的问题。但是你仍然需要处理更快的移动。我假设计时器正在运行一些任务,这迫使UI每1.5秒钟重绘一次。因此在改变,为0.700应该做的伎俩 –

回答

1

好只是一个建议,改变你的detectHits从()方法(INT ... INT ...)到(MotionEvent ...)缩短了通话。

对于一个随机颜色,你将哈贝编程生成一个。 有这个Color.rgb(int red, int green, int blue)方法,你可能想要使用。

所以,现在你要做的就是,你生成随机整数生成一个颜色,这样

Random rnd = new Random(); 
Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254)); 

现在你将有TI应用该颜色。 首先,它不鼓励在onDraw期间分配对象,所以将Paint的分配移至onCreate/onResume并使其成为过程中的字段。那么你将不得不像这样调整你的onTouchMethod。

public boolean onTouch(View v, MotionEvent event) { 
if (detectHit(event)) { 
    changeColor(); 
    score++; 
    invalidate(); 
} 
return false; 

private void changeColor(){ 
    Random rnd = new Random(); 
    Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254)); 
    dotPaint.setColor(rndCol); // this should be a field by now and accessible from within this method 
} 
在1.5改变速度到0.7的物质

使在类中的定时的字段,并且在某一点减少该值以减少定时器。

由于您没有显示您目前每1.5秒移动一次广场,我无法为您调整代码。

+0

好吧,我现在明白了随机颜色除了它说dotPaint解决不了.. –

+0

这里是如何我移动的方每1.5秒。 timer = new Timer(); task = new DotSmasherTimerTask(canvas); timer.schedule(task,0,1500); –

+0

是的,它不能被解决,因为我猜你没有阅读文本:) 你将不得不在你的课堂上做一个字段,或者你不能在那个时候访问它。 –