2013-06-26 1 views
0

나는 간단한 응용 프로그램을 작성하기 시작한 입니다. 클래스 확장보기를 사용하고 간단한 게임을 만들기 위해 일부 스레드를 사용합니다. 방향이 잘못되었는지 물어보고 싶습니까? 다른 방법으로 사용해야합니까? 내가 여기에 스레드를 사용하는 것이 잘못되었다고 생각합니까 ?? 난 그냥 당신은 onDraw에서 invalidate 호출해서는 안나는 잘못 가고 있니? ondraw 및 스레드를 사용하여 애니메이션 게임을 만들 수 있습니다.

public class Game extends View { 
Bitmap background; 
Bitmap nomouthbear; 
Bitmap nomouthbearget; 
Bitmap apple; 
float bearX; 
float bearY; 
List<Apple> appleList; 
int appleCount = 0; 
float appleX; 
float appleY; 
float applescore; 
float applespeed; 
int totalscore = 0; 
float canvasheight; 
float canvaswidth; 
float randomNumber;// random number for apple appear in X 
float randomNumber2;// random number for score and speed 
float randomNumber3; 
int applecombo = 0; // count for how many apple that the bear eat in combo 
boolean checkbeareat; // for check if bear eat any of apple or not. 
boolean bearEating = false; 
Thread thread2; 
boolean ineatingthread = false; 

int time = 20; // game time =60sec 

public Game(Context context) { 
    super(context); 

    // setup image source 
    nomouthbear = BitmapFactory.decodeResource(getResources(), 
      R.drawable.nomouthbear_net); 
    apple = BitmapFactory.decodeResource(getResources(), R.drawable.apple); 
    nomouthbearget = BitmapFactory.decodeResource(getResources(), 
      R.drawable.nomouthbearget); 
    background = BitmapFactory.decodeResource(getResources(), 
      R.drawable.background); 
    // init bear x,y 
    bearX=0; 
    bearY =0; 
    // setup background 
    if (background != null) { 
     setBackgroundDrawable(new BitmapDrawable(background)); 
    } 
    // open a list which hold all apple 
    appleList = new ArrayList<Apple>(); 

    // make a thread to creat apple every 2 sec 
    Thread thread = new Thread() { 
     @Override 
     public void run() { 
      try { 
       while (true) { 
        sleep(2000); 
        randomNumber = (float) Math.random(); 
        randomNumber2 = (float) Math.random(); 

        // avoid start at edge point 

        appleX = canvaswidth * randomNumber; 
        if (appleX >= canvaswidth - apple.getWidth()/2) 
         appleX = canvaswidth - apple.getWidth()/2; 
        if (appleX <= nomouthbear.getWidth()/2) 
         appleX = nomouthbear.getWidth(); 
        applescore = 1000 * randomNumber2; 
        // check if speed too low 
        applespeed = 10 * randomNumber2; 
        if (applespeed <= 3) { 
         applespeed = 3; 
        } 
        // add new apple in the apple list 
        appleList.add(new Apple(appleX, 65, applescore, 
          applespeed)); 
        appleCount++; 

       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 
    // start the thread 
    thread.start(); 
    // thread for timer 

    Thread thread1 = new Thread() { 
     @Override 
     public void run() { 
      try { 
       while (true) 

       { 

         sleep(1000); 
         if(time>=0) 
        time--; 

       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 
    thread1.start(); 

//thread for controlling the bear eat pic appear time  
    Thread thread2 = new Thread() { 
     @Override 
     public void run() { 
      try { 
       while (true) 

       { 

        if (bearEating == true) { 

          sleep(200); 
          bearEating = false; 

        } 


       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 
    thread2.start(); 




} 

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 



    if (time <= 0) { 
     Paint textPaint = new Paint(); 
     textPaint.setColor(Color.BLACK); 
     textPaint.setTextAlign(Align.LEFT); 
     textPaint.setTextSize(65); 
     canvas.drawText(
       "Game Over!", 
       canvas.getWidth()/4, canvas.getHeight()/2, textPaint); 
     canvas.drawText(
       "Your Score is ", 
       canvas.getWidth()/4, canvas.getHeight()/2+65, textPaint); 
     canvas.drawText(
       Integer.toString(totalscore), 
       canvas.getWidth()/4, canvas.getHeight()/2+130, textPaint); 






    } else { 
     checkbeareat = false; 
     canvasheight = canvas.getHeight(); 
     canvaswidth = canvas.getWidth(); 
     // draw score text 
     Paint textPaint = new Paint(); 
     textPaint.setColor(Color.BLACK); 
     textPaint.setTextAlign(Align.LEFT); 
     textPaint.setTextSize(65); 
     canvas.drawText("Score: " + Integer.toString(totalscore), 50, 50, 
       textPaint); 
     canvas.drawText("Time left: " + Integer.toString(time), 50, 120, 
       textPaint); 
     // if have apple 
     if (appleCount != 0) { 
      for (int i = 0; i < appleCount; i++) { 
       if (appleList.get(i).checkstate()) { 

        // make every apple fall down 

        if ((appleList.get(i).getAppleY() + apple.getHeight()/2) <= canvas 
          .getHeight()) { 

         appleList.get(i).setAppleY(
           appleList.get(i).getAppleY() 
             + appleList.get(i).getspeed()); 
        } else { 
         // appleList.get(i).setAppleY(appleList.get(i).getAppleY()); 
         applecombo = 0; 
         appleList.get(i).destoryApple(); 
        } 

        // check if bear eat the apple 

        if (bearX + nomouthbear.getWidth()/2 >= appleList 
          .get(i).getAppleX() 
          && bearX <= appleList.get(i).getAppleX() 
          && bearY>= appleList 
            .get(i).getAppleY() 
          && bearY-nomouthbear.getHeight()/2 <= appleList.get(i).getAppleY()) { 
         // add score 
         totalscore += appleList.get(i).getAppleScore(); 
         // change the state of apple to false so wont draw 
         // it 
         // again 
         appleList.get(i).destoryApple(); 
         // draw bear ate 
         canvas.drawBitmap(nomouthbearget, bearX 
           - nomouthbear.getWidth()/2, bearY 
           - nomouthbear.getHeight(), null); 
         checkbeareat = true; 
         bearEating = true; 

         applecombo++; 

        } 

        // draw apple 
        if (appleList.get(i).checkstate()) { 
         canvas.drawBitmap(
           apple, 
           appleList.get(i).getAppleX() 
             - (apple.getWidth()/2), 
           appleList.get(i).getAppleY() 
             - (apple.getHeight()/2), null); 
        } 

       } 
      } 
     } 

     // draw bear 
     // canvas.drawBitmap(nomouthbear, 0, 0, null); 
     if (bearEating == false) { 

       if (bearX == 0 && bearY == 0){ 

        canvas.drawBitmap(nomouthbear, 0, canvas.getHeight()- nomouthbear.getHeight()*2, null);} 

       else{ 
        canvas.drawBitmap(nomouthbear, 
          bearX - nomouthbear.getWidth()/2, bearY 
            - nomouthbear.getHeight(), null);} 


     } else { 
      canvas.drawBitmap(nomouthbearget, 
        bearX - nomouthbear.getWidth()/2, 
        bearY - nomouthbear.getHeight(), null); 
     } 
     invalidate(); 
    } 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    // TODO Auto-generated method stub 

    if (event.getX() >= nomouthbear.getWidth()/2 
      && event.getX() <= canvaswidth - nomouthbear.getWidth()/2) { 
     bearX = event.getX(); 
    } else if (event.getX() >= canvaswidth - nomouthbear.getWidth()/2) 
     bearX = canvaswidth - nomouthbear.getWidth()/2; 
    else 
     bearX = nomouthbear.getWidth()/2; 

    bearY = canvasheight - nomouthbear.getHeight(); 

    return true; 
} 

} 

답변

0

활동을 확장 클래스에서이 전화를

Game gameview; 
gameview= new Game(this); 
setContentView(gameview); 

를 사용 - invalidateonDraw가 호출되도록 것입니다. 뷰를 주기적으로 업데이트하려면 실행 빈을 뷰에 게시하여 스레드 (예 : Thread1)의 일정 간격으로 invalidate으로 호출해야합니다.

멀티 스레딩의 경우 코드가 완전히 안전하지 않습니다 (예 : 예측할 수 없음). 동기화가 없거나 휘발성 물질을 사용하지 않습니다.

0

UI 스레드에서 렌더링과 계산을 모두 처리하므로 상황이 조금 복잡해지면 느리게 진행되므로 가장 간단한 게임 만 사용해도 무방합니다.

당신은 GLSurfaceView를 사용한다, 그 문서를 확인하고 OpenGL in Android

에 읽어 당신이 정말 정규 SurfaceView을 고려, OpenGL을 사용하지 않으려면, 그러나 약간은 알고 있어야 설정이 번거 롭고 원활하게 수행 할 수 없습니다.

+0

덕분에 나는 openGL을 통해 갈 것입니다. – user2524336

0

보기 및 onDraw를 사용하여 게임을 간단하게 만들 수 있지만 매우 느리고 매우 유익합니다. 당신은 그것을 사용하여 좋은 게임을 만들 수 없습니다. 게임을 만들려면 openGL (GLSurfaceView)을 사용해야합니다. 나는 당신에게 책을 권합니다 : J. F. DiMarzio 실용적인 안드로이드 4 게임 개발 안드로이드에서 OpenGL을 사용하여 배우는 것이 좋은 책입니다.

관련 문제