標籤:
public class PinBall extends Activity{ private int tableHeight; private int tableWidth; Random random = new Random(); //擋板大小和座標 private final int racket_width = 70; private final int racket_height = 20; private int racketY; private int racketX; //球體大小,速度,座標 private final int ballR = 12; private int ballX; private int ballY; private int Vy = 3; //產生一個比率(-0.5~0.5之間),用於產生隨機方向 private double xyRate = random.nextDouble() - 0.5; private int Vx = (int) (Vy * 2 * xyRate); //遊戲進行時標誌 private boolean isLose = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //全屏無標題 requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //設定遊戲介面 final GameView game = new GameView(this); setContentView(game); //擷取案頭大小 WindowManager manager = getWindowManager(); Display display = manager.getDefaultDisplay(); tableHeight = display.getHeight(); tableWidth = display.getWidth(); //根據擷取的案頭大小初始化座標 initXY(); //重繪 final Handler handler = new Handler(){ public void handleMessage(Message message){ if(message.what == 0x123){ game.invalidate(); } } }; final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { //左右邊框 if(ballX < 0 || (ballX + ballR > tableWidth)){ Vx = -Vx; } //超過下邊界且未被球拍接住 if((ballY + ballR > racketY) && (ballX + ballR < racketX || ballX > racketX + racket_width)){ timer.cancel(); isLose = true; } //被球拍打回或者反彈時到達頂部 if(ballY < 0 || (ballY + ballR > racketY && ballX > racketX && ballX < racketX + racket_width )){ Vy = -Vy; } ballX += Vx; ballY += Vy; handler.sendEmptyMessage(0x123); } }, 0, 10); //給遊戲view加監聽器 game.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int x = (int) event.getX(); int mid = tableWidth/2; switch (x > mid ? 1 : 2) { case 1: if(racketX + racket_width < tableWidth){ racketX += 10; } break; case 2: if(racketX > 0){ racketX -= 10; } break; } game.invalidate(); return true; } }); } private void initXY(){ racketY = tableHeight - 80; racketX = random.nextInt(tableWidth); ballX = random.nextInt(tableWidth); ballY = random.nextInt(10) + 20; } class GameView extends View{ private static final float TEXT_SIZE = 40; public GameView(Context context) { super(context); // TODO Auto-generated constructor stub setFocusable(true); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); //遊戲結束 if (isLose) { paint.setTextSize(TEXT_SIZE); paint.setColor(Color.RED); canvas.drawText("Game Over!", tableWidth/2 - paint.getTextSize()*2, tableHeight/2 - paint.getTextSize()/2, paint); } //遊戲繼續 else { paint.setColor(Color.BLUE); canvas.drawCircle(ballX, ballY, ballR, paint); paint.setColor(Color.GREEN); canvas.drawRect(racketX, racketY, racketX + racket_width, racketY + racket_height, paint); } } }}
安卓遊戲開發_基礎環境擷取代碼