最近學習了android 2D 應用的開發,拿來和大家分享一下,學習2D 開發前我們先了解一下SurfaceView的使用以及貼圖技術的使用,最後呢,是一個簡單的2的游戲的實現。
1.SurfaceView的一些用法
提供了一個專門的繪圖渲染的圖形嵌入在一個視圖層次;SurfaceView負責將圖形正確的顯示在屏幕上,訪問底層圖形是通過SurfaceHolder提供接口,可通過調用getHolder(),圖形創建SurfaceView的窗口是可見的;實現方法是surfaceCreated(SurfaceHolder)和surfaceDestroyed(SurfaceHolder)銷毀圖形
簡單的例子如下
[java]
package com.nyist.wj;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceViewActivity extends Activity {
MySurfaceView mySurfaceView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
}
public class MySurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
SurfaceViewActivity surfaceViewActivity; // Activity的引用
Paint paint; // 畫筆的引用
public MySurfaceView(Context context) // 構造器
{
super(context);
this.surfaceViewActivity = (SurfaceViewActivity) context; // 拿到Activity引用
this.getHolder().addCallback(this); // 設置生命周期回調接口的實現者
paint = new Paint(); // 創建畫筆
paint.setAntiAlias(true); // 打開抗鋸齒
}
@Override
protected void onDraw(Canvas canvas) // onDraw方法
{
paint.setColor(Color.WHITE); // 設置畫筆顏色為白色
canvas.drawRect(0, 0, getWidth(), getHeight(), paint); // 繪制白色矩形背景
paint.reset(); // 清除畫筆設置
paint.setARGB(50, 0, 255, 0); // 設置畫筆顏色和透明度
paint.setStrokeWidth(5); // 設置畫筆寬度
RectF rf = new RectF(50, 100, 160, 180); // 創建一個矩形
canvas.drawRect(rf, paint); // 繪制矩形
paint.setARGB(50, 0, 0, 255); // 設置畫筆顏色和透明度
paint.setStyle(Style.STROKE); // 設置風格為邊框
paint.setStrokeWidth(5); // 設置畫筆寬度
Rect r = new Rect(200, 100, 300, 180); // 創建一個矩形
canvas.drawRect(r, paint); // 畫一個矩形邊框
paint.setColor(Color.RED); // 設置畫筆顏色
paint.setAntiAlias(true); // 打開抗鋸齒
canvas.drawCircle(100, 250, 30, paint);// 畫一個圓
paint.setColor(Color.YELLOW); // 設置畫筆顏色
rf = new RectF(200, 250, 300, 300); // 創建一個矩形
canvas.drawOval(rf, paint); // 畫一個橢圓,充滿矩形
paint.reset(); // 清除畫筆設置
paint.setColor(Color.RED); // 設置畫筆顏色
paint.setTextSize(40); // 設置文字大小
paint.setStyle(Style.FILL_AND_STROKE);
canvas.drawText("loading...", 50, 350, paint); // 畫一個字符串
}
@Override
public void surfaceCreated(SurfaceHolder holder) // 創建時被調用
{
Canvas canvas = holder.lockCanvas(); // 獲取畫布
try {
synchronized (holder) {
onDraw(canvas);
} // 繪制
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
} // 繼承方法,空實現
@Override
// 繼承方法,空實現
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
}
}
實現的效果是:
2.貼圖技術的使用
貼圖技術主要包括圖片的移動、旋轉、透明度、等變化
下面是關於貼圖技術的使用方法 首先是自定義的一個布局
[html]
<com.nyist.wj.MysurfaceView
android:id="@+id/mysurfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
然後就是實現自定義布局引用的類
[java]
package com.nyist.wj;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MysurfaceView extends View {
Bitmap bitmap;
Paint paint;
public MysurfaceView(Context context,AttributeSet attributeSet) {
super(context,attributeSet);
// TODO Auto-generated constructor stub
this.initBitmap();
}
public void initBitmap() {
// TODO Auto-generated method stub
paint=new Paint();
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ball);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//打開抗鋸齒
paint.setAntiAlias(true);
canvas.drawBitmap(bitmap, 50,50,paint);
canvas.save();
Matrix matrix=new Matrix();
//移動
matrix.setTranslate(100, 100);
Matrix matrix2=new Matrix();
// 旋轉
matrix2.setRotate(50);
Matrix matrix3=new Matrix();
matrix3.setConcat(matrix, matrix2);
//縮放
matrix.setScale(0.5f, 0.5f);
matrix2.setConcat(matrix3, matrix);
canvas.drawBitmap(bitmap, matrix2, paint);
canvas.restore();
canvas.save();
paint.setAlpha(200);
matrix.setTranslate(150, 150);
//放大
matrix2.setScale(1.3f, 1.3f);
//設置總矩陣
matrix3.setConcat(matrix, matrix2);
canvas.drawBitmap(bitmap, matrix3, paint);
paint.reset();
}
}
實現的效果如下 解釋一下:這是橫屏顯示的結果,左上方是原圖片大小 接著是縮放的和放大的圖片
3.廣告條的實現方法
廣告雖不好,但是這確實為android開發者提供了一點微薄的力量,下面就看看廣告條的開發
效果圖:
實現的過程有自定義的View
[html]
<com.nyist.wj.myView
android:layout_width="fill_parent"
android:layout_height="50dip"
/>
實現view的方法
[java]
package com.nyist.wj;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class myView extends View {
Bitmap[] bitmap;
int currentindex = 1;
int time = 3000;
boolean isAnima = false;
Paint paint;
int[] imageID;
// 初始化圖片數阻
boolean initFlag = false;
float prex, prey;
int xoffset;
public myView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
// TODO Auto-generated constructor stub
this.imageID = new int[] { R.drawable.test1, R.drawable.test2,
R.drawable.test3, R.drawable.test4 };
// 生成圖片數組
bitmap = new Bitmap[imageID.length];
paint = new Paint();
// 抗鋸齒
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
this.setOnTouchListener(null);
new Thread() {
public void run() {
while (true) {
if (!isAnima) {
currentindex = (currentindex + 1) % imageID.length;
}
// 刷幀重繪
myView.this.postInvalidate();
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handthele exception
}
}
};
}.start();
}
public void initBitmap() {
Resources resources = this.getResources();
for (int i = 0; i < imageID.length; i++) {
// ------------------------------
// 實現圖片 的縮放
bitmap[i] = scaleChange(BitmapFactory.decodeResource(resources,
imageID[i]
));
}
}
public static Bitmap scaleChange(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
double xratio = (double) Constant.SCREEN_WIDTH / w;
double yratio = 50.0 / h;
// 生成矩陣
Matrix matrix = new Matrix();
matrix.postScale((float) xratio, (float) yratio);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return result;
}
@Override
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
// 第一次運行onDraw方法的時候,調用初始化圖片數組的方法
if (!initFlag) {
initBitmap();
initFlag = true;
}
if (canvas == null) {
return;
}
if (!isAnima) {
// -------------------------------------
// 當沒有播放動畫時候繪制當前圖片
drawAD(canvas, xoffset, currentindex);
}
if (isAnima) {
// 當向右滑動時候
if (xoffset > 0) {
int size = imageID.length;
// 得到上一張圖片的索引
int preIndex = (currentindex - 1 + size) % size;
// 根據x軸偏移量,算出上一張圖片繪制時的x坐標
int nextIndex = xoffset - Constant.SCREEN_WIDTH;
// 繪制當前索引圖片
drawAD(canvas, xoffset, (preIndex + 1) % size);
drawAD(canvas, nextIndex, preIndex);
} // 當往左抹時
else if (xoffset < 0) {
int size = imageID.length;
// 得到下一張圖片的索引
int preIndex = (currentindex + 1 + size) % size;
int nextIndex = xoffset + Constant.SCREEN_WIDTH;
// 繪制當前圖片的索引
drawAD(canvas, xoffset, (preIndex - 1 + size) % size);
drawAD(canvas, nextIndex, preIndex);
}
}
}
public void drawAD(Canvas canvas, int offset, int Index) {
canvas.drawBitmap(bitmap[Index], offset, 0, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prex = x;
prey = y;
System.out.println("------------------------------------");
System.out.println("+++++++++++++++++++++++++++++++++++"
+ currentindex);
return true;
case MotionEvent.ACTION_MOVE:
if (!isAnima && Math.abs(x - prex) > 10) {
isAnima = true;
}
if (isAnima) {
xoffset = (int) (xoffset + x - prex);
prex = x;
prey = y;
}
this.postInvalidate();
return true;
case MotionEvent.ACTION_UP:
if (isAnima) {
if (x < Constant.SCREEN_WIDTH / 4 && xoffset < 0) {
int size = imageID.length;
currentindex = (currentindex + 1) % size;
} else if (x > Constant.SCREEN_WIDTH * 3 / 4 && xoffset > 0) {
int size = imageID.length;
currentindex = (currentindex - 1 + size) % size;
}
}
isAnima = false;
xoffset = 0;
this.postInvalidate();
return true;
}
return false;
}
}
接著是在activity中的插入
[java]
package com.nyist.wj;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
public class GuangGaoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
DisplayMetrics displayMetrics=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
Constant.SCREEN_HEIGHT=displayMetrics.heightPixels; //獲取具體的屏幕分辨率數值
Constant.SCREEN_WIDTH=displayMetrics.widthPixels;
}
}
4.下面是介紹2D下簡單的游戲開發
效果圖如下
主要用到的SurfaceView 和貼圖技術以及聲音的處理
用到的處理方法共有5個類
1.BallGameActivity 設置屏幕的相關屬性
2.GameSurfaceView 實現顯示界面的設置
3.ThreadForDraw 刷幀線程重新繪制游戲界面
4.ThreadForGo 控制小球移動
5.ThreadForTimecControl 計算小球運行的時間
下面分別介紹每個類是如何實現的
1.BallGameActivity
[java]
package com.nyist.wj;
import java.util.HashMap;
import org.apache.http.auth.AUTH;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class BallGameActivity extends Activity {
GameSurfaceView gameSurfaceView;
// 聲音緩沖池
SoundPool soundPool;
// 存放聲音ID的 map
HashMap<Integer, Integer> soundpoolMap;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 初始化聲音
initSounds();
// 設置全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
gameSurfaceView = new GameSurfaceView(this);
setContentView(gameSurfaceView);
// 循環播放音樂
playSound(1, -1);
}
public void playSound(int sound, int loop) {
// TODO Auto-generated method stub
// 播放聲音的方法
AudioManager audioManager = (AudioManager) this
.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeMax = audioManager
.getStreamMaxVolume(audioManager.STREAM_MUSIC);
float streamVolumeCurrent = audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
// 參數 聲音資源的ID 左聲道 右聲道 優先級 循環次數 回訪速度
soundPool.play(soundpoolMap.get(sound), volume, volume, 1, loop, 0.5f);
}
public void initSounds() {
// TODO Auto-generated method stub
// 參數 播放的個數 音頻類型 播放的質量
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
// 創建聲音資源的MAP
soundpoolMap = new HashMap<Integer, Integer>();
// 將加載聲音的資源 放在map中
soundpoolMap.put(1, soundPool.load(this, R.raw.bg, 1));
}
}
2.GameSurfaceView
[html]
package com.nyist.wj;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
BallGameActivity ballGameActivity;
ThreadForTimecControl threadForTimecControl;
ThreadForGo threadForGo;
ThreadForDraw threadForDraw;
int backSize = 16; // 背景塊大小
int screenWidth = 320; // 屏幕寬度
int screenHeight = 480; // 屏幕高度
int bannerWidth = 40; // 擋板寬度
int bannerHeight = 6; // 擋板高度
int bottomSpance = 16; // 下端留白
int bannerSpan = 5; // 板每次移動的距離
int ballSpan = 8; // 球每次移動的距離
int ballSize = 16; // 小球大小
int hintWidth = 100; // 游戲說明寬度
int hintHeight = 20; // 游戲說明高度
int status = 0; // 游戲狀態控制 0-等待開始 1-進行中 2-游戲結束 3-游戲勝利
int score = 0; // 得分
int ballx; // 小球x坐標
int bally; // 小球y坐標
int direction = 0; // 小球方向
int bannerX; // 擋板X坐標
int bannerY; // 擋板Y坐標
int scoreWidth = 32;
Bitmap iback; // 背景圖
Bitmap[] iscore = new Bitmap[10];// 得分圖
Bitmap iball; // 小球用圖
Bitmap ibanner; // 擋板用圖
Bitmap ibegin; // 開始用圖
Bitmap igameover; // 游戲結束用圖
Bitmap iwin; // 游戲結束用圖
Bitmap iexit; // 退出用圖
Bitmap ireplay; // 重玩用圖
public GameSurfaceView(BallGameActivity ballGameActivity) {
super(ballGameActivity);
// 注冊回調接口
getHolder().addCallback(this);
this.ballGameActivity = ballGameActivity;
initBitmap();
// /////////----------------------------------------------
threadForDraw = new ThreadForDraw(this);
// TODO Auto-generated constructor stub
}
public void initBitmap() {
iback = BitmapFactory.decodeResource(getResources(), R.drawable.back);
iscore[0] = BitmapFactory.decodeResource(getResources(), R.drawable.d0);
iscore[1] = BitmapFactory.decodeResource(getResources(), R.drawable.d1);
iscore[2] = BitmapFactory.decodeResource(getResources(), R.drawable.d2);
iscore[3] = BitmapFactory.decodeResource(getResources(), R.drawable.d3);
iscore[4] = BitmapFactory.decodeResource(getResources(), R.drawable.d4);
iscore[5] = BitmapFactory.decodeResource(getResources(), R.drawable.d5);
iscore[6] = BitmapFactory.decodeResource(getResources(), R.drawable.d6);
iscore[7] = BitmapFactory.decodeResource(getResources(), R.drawable.d7);
iscore[8] = BitmapFactory.decodeResource(getResources(), R.drawable.d8);
iscore[9] = BitmapFactory.decodeResource(getResources(), R.drawable.d9);
iball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
ibanner = BitmapFactory.decodeResource(getResources(),
R.drawable.banner);
ibegin = BitmapFactory.decodeResource(getResources(), R.drawable.begin);
igameover = BitmapFactory.decodeResource(getResources(),
R.drawable.gameover);
iwin = BitmapFactory.decodeResource(getResources(), R.drawable.win);
iexit = BitmapFactory.decodeResource(getResources(), R.drawable.exit);
ireplay = BitmapFactory.decodeResource(getResources(),
R.drawable.replay);
// 初始化小球位置及板X坐標
initBallAndBanner();
}
public void initBallAndBanner() {
// 初始化小球位置
bally = screenHeight - bottomSpance - bannerHeight - ballSize;
ballx = screenWidth / 2 - ballSize / 2;
// 初始化板X坐標
bannerX = screenWidth / 2 - bannerWidth / 2;
bannerY = screenHeight - bottomSpance - bannerHeight;
}
public void replay() {
if (status == 2 || status == 3) {
// 初始化小球的位置
initBallAndBanner();
score = 0;
status = 0;
direction = 3;
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// 清除背景
int colum = screenWidth / backSize
+ ((scoreWidth % backSize == 0) ?0:1);
int rows = screenHeight / backSize
+ ((screenHeight % backSize == 0) ? 0 : 1);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < colum; j++) {
canvas.drawBitmap(iback, 16*j, 16*i, null);
}
}
// 繪制得分
String scorestr = score + "";
int loop = 3 - scorestr.length();
for (int i = 0; i < loop; i++) {
scorestr = "0" + scorestr;
}
int startX = screenWidth - scoreWidth * 3 - 10;
for (int i = 0; i < 3; i++) {
int tempScore = scorestr.charAt(i) - '0';
canvas.drawBitmap(iscore[tempScore], startX + i * scoreWidth, 5,
null);
}
// 繪制小球
canvas.drawBitmap(iball, ballx, bally, null);
// 繪制板
canvas.drawBitmap(ibanner, bannerX, bannerY, null);
// 繪制開始提示
if (status == 0) {
canvas.drawBitmap(ibegin, screenWidth / 2 - hintWidth / 2,
screenHeight / 2 - hintHeight / 2, null);
}
// 繪制失敗提示
if (status == 2) {
canvas.drawBitmap(igameover, screenWidth / 2 - hintWidth / 2,
screenHeight / 2 - hintHeight / 2, null);
}
// 繪制勝利提示
if (status == 3) {
canvas.drawBitmap(iwin, screenWidth / 2 - hintWidth / 2,
screenHeight / 2 - hintHeight / 2, null);
}
// 繪制退出提示
canvas.drawBitmap(iexit, screenWidth - 32, screenHeight - 16, null);
// /繪制重玩提示
if (status == 2 || status == 3) {
canvas.drawBitmap(ireplay, 0, screenHeight - 16, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if (x < screenWidth && x > screenWidth - 32 && y < screenHeight
&& y > screenHeight - 16) {
// ----------------------------------------------------------
// 按下退出選項退出系統
ballGameActivity.soundPool.stop(1);
System.exit(0);
}
// 等待狀態
if (status == 0) {
status = 1;
// ----------------------------------------------
threadForTimecControl = new ThreadForTimecControl(this);
threadForGo = new ThreadForGo(this);
threadForTimecControl.start();
threadForGo.start();
} else if (status == 1) {
bannerX = x;
} else if (status == 2 || status == 3) {
if (x < 32 && x > 0 && y < screenHeight && y > screenHeight - 16) {
//按下重玩
replay();
}
}
// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// ----------------------------------
// 創建時候啟動相關進程
this.threadForDraw.flag = true;
threadForDraw.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 釋放相應的進程
boolean retry = true;
this.threadForDraw.flag = false;
// 不斷的循環知道刷幀結束
while (retry) {
try {
threadForDraw.join();
retry = false;
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}
}
3.ThreadForDraw
[java]
package com.nyist.wj;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class ThreadForDraw extends Thread {
boolean flag=true;
int sleep=100;
GameSurfaceView gameSurfaceView;
SurfaceHolder surfaceHolder;
public ThreadForDraw (GameSurfaceView gameSurfaceView){
this.gameSurfaceView=gameSurfaceView;
this.surfaceHolder=gameSurfaceView.getHolder();
}
@Override
public void run() {
// TODO Auto-generated method stub
Canvas canvas;
while (this.flag) {
canvas=null;
try {
canvas=this.surfaceHolder.lockCanvas(null);
synchronized (this.surfaceHolder) {
gameSurfaceView.onDraw(canvas);
}
} catch (Exception e) {
}finally{
if (canvas!=null) {
this.surfaceHolder.unlockCanvasAndPost(canvas);
}
}
try {
Thread.sleep(sleep);
} catch (Exception e) {
// TODO: handle exception
}
}
super.run();
}
}
4.ThreadForGo
[java]
package com.nyist.wj;
//游戲過程中移動小球的線程
public class ThreadForGo extends Thread {
// 設置線程執行的標志
boolean flag = true;
// 游戲界面的引用
GameSurfaceView gameSurfaceView;
public ThreadForGo(GameSurfaceView gameSurfaceView) {
this.gameSurfaceView = gameSurfaceView;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (flag) {
switch (gameSurfaceView.direction) {
case 0:
// 右上控制當前方向移動球
gameSurfaceView.ballx = gameSurfaceView.ballx
+ gameSurfaceView.ballSpan;
gameSurfaceView.bally = gameSurfaceView.bally
- gameSurfaceView.ballSpan;
// 判斷是否碰壁
if (gameSurfaceView.ballx >= gameSurfaceView.screenWidth
- gameSurfaceView.ballSize) {
// 碰到上壁
gameSurfaceView.direction = 3;
} else if (gameSurfaceView.bally <= 0) {
gameSurfaceView.direction = 1;
}
break;
case 1:
// 右下
gameSurfaceView.ballx = gameSurfaceView.ballx
+ gameSurfaceView.ballSpan;
gameSurfaceView.bally = gameSurfaceView.bally
+ gameSurfaceView.ballSpan;
// 碰到下壁
if (gameSurfaceView.bally >= gameSurfaceView.screenHeight
- gameSurfaceView.bannerHeight
- gameSurfaceView.bottomSpance
- gameSurfaceView.ballSize) {
// /-----------------------------------------
checkCollision(1);
// 碰到右臂
} else if (gameSurfaceView.ballx >= gameSurfaceView.screenWidth
- gameSurfaceView.ballSize) {
gameSurfaceView.direction = 2;
}
break;
case 2:
// 左下
gameSurfaceView.ballx = gameSurfaceView.ballx
- gameSurfaceView.ballSpan;
gameSurfaceView.bally = gameSurfaceView.bally
+ gameSurfaceView.ballSpan;
// 碰到下壁
if (gameSurfaceView.bally >= gameSurfaceView.screenHeight
- gameSurfaceView.bannerHeight
- gameSurfaceView.bottomSpance
- gameSurfaceView.ballSize) {
// ////////////////////-----------------------------------
checkCollision(2);
}
// 碰到左壁
else if (gameSurfaceView.ballx <= 0) {
gameSurfaceView.direction = 1;
}
break;
case 3:
gameSurfaceView.ballx = gameSurfaceView.ballx
- gameSurfaceView.ballSpan;
gameSurfaceView.bally = gameSurfaceView.bally
- gameSurfaceView.ballSpan;
// /碰到左壁
if (gameSurfaceView.ballx <= 0) {
gameSurfaceView.direction = 0;
}
// 碰到上壁
else if (gameSurfaceView.bally <= 0) {
gameSurfaceView.direction = 2;
}
break;
default:
break;
}
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
public void checkCollision(int dirction) {
if (gameSurfaceView.ballx >= gameSurfaceView.bannerX
- gameSurfaceView.ballSize
&& gameSurfaceView.ballx <= gameSurfaceView.bannerX
+ gameSurfaceView.bannerWidth) {
switch (dirction) {
case 1:
gameSurfaceView.direction = 0;
break;
case 2:
gameSurfaceView.direction = 3;
break;
default:
break;
}
} else {
// 沒有碰到板
gameSurfaceView.threadForTimecControl.flag = false;
gameSurfaceView.threadForGo.flag = false;
gameSurfaceView.status = 2;
}
}
}
5.ThreadForTimecControl
[java]
package com.nyist.wj;
public class ThreadForTimecControl extends Thread {
//計算生存時間的線程
//判斷是否勝利的值
int highest = 200;
// 游戲界面的引入
GameSurfaceView gameSurfaceView;
//線程標志位
boolean flag = true;
public ThreadForTimecControl(GameSurfaceView gameSurfaceView) {
this.gameSurfaceView = gameSurfaceView;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(flag){
gameSurfaceView.score++;
if (gameSurfaceView.score==highest) {
//游戲勝利
gameSurfaceView.status=3;
//----------------------------------------
gameSurfaceView.threadForTimecControl.flag=false;
gameSurfaceView.threadForGo.flag=false;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}