当前位置:   article > 正文

android 2D 游戏的开发的方法_利用android studio开发二维游戏平台

利用android studio开发二维游戏平台

                                 最近学习了android 2D 应用的开发,拿来和大家分享一下,学习2D 开发前我们先了解一下SurfaceView的使用以及贴图技术的使用,最后呢,是一个简单的2的游戏的实现。


 1.SurfaceView的一些用法


                     提供了一个专门的绘图渲染的图形嵌入在一个视图层次;SurfaceView负责将图形正确的显示在屏幕上,访问底层图形是通过SurfaceHolder提供接口,可通过调用getHolder(),图形创建SurfaceView的窗口是可见的;实现方法是surfaceCreated(SurfaceHolder)和surfaceDestroyed(SurfaceHolder)销毁图形

 


                    简单的例子如下

  1. package com.nyist.wj;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.graphics.Canvas;
  5. import android.graphics.Color;
  6. import android.graphics.Paint;
  7. import android.graphics.Rect;
  8. import android.graphics.RectF;
  9. import android.graphics.Paint.Style;
  10. import android.os.Bundle;
  11. import android.view.SurfaceHolder;
  12. import android.view.SurfaceView;
  13. public class SurfaceViewActivity extends Activity {
  14. MySurfaceView mySurfaceView;
  15. /** Called when the activity is first created. */
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. mySurfaceView = new MySurfaceView(this);
  20. setContentView(mySurfaceView);
  21. }
  22. public class MySurfaceView extends SurfaceView implements
  23. SurfaceHolder.Callback {
  24. SurfaceViewActivity surfaceViewActivity; // Activity的引用
  25. Paint paint; // 画笔的引用
  26. public MySurfaceView(Context context) // 构造器
  27. {
  28. super(context);
  29. this.surfaceViewActivity = (SurfaceViewActivity) context; // 拿到Activity引用
  30. this.getHolder().addCallback(this); // 设置生命周期回调接口的实现者
  31. paint = new Paint(); // 创建画笔
  32. paint.setAntiAlias(true); // 打开抗锯齿
  33. }
  34. @Override
  35. protected void onDraw(Canvas canvas) // onDraw方法
  36. {
  37. paint.setColor(Color.WHITE); // 设置画笔颜色为白色
  38. canvas.drawRect(0, 0, getWidth(), getHeight(), paint); // 绘制白色矩形背景
  39. paint.reset(); // 清除画笔设置
  40. paint.setARGB(50, 0, 255, 0); // 设置画笔颜色和透明度
  41. paint.setStrokeWidth(5); // 设置画笔宽度
  42. RectF rf = new RectF(50, 100, 160, 180); // 创建一个矩形
  43. canvas.drawRect(rf, paint); // 绘制矩形
  44. paint.setARGB(50, 0, 0, 255); // 设置画笔颜色和透明度
  45. paint.setStyle(Style.STROKE); // 设置风格为边框
  46. paint.setStrokeWidth(5); // 设置画笔宽度
  47. Rect r = new Rect(200, 100, 300, 180); // 创建一个矩形
  48. canvas.drawRect(r, paint); // 画一个矩形边框
  49. paint.setColor(Color.RED); // 设置画笔颜色
  50. paint.setAntiAlias(true); // 打开抗锯齿
  51. canvas.drawCircle(100, 250, 30, paint);// 画一个圆
  52. paint.setColor(Color.YELLOW); // 设置画笔颜色
  53. rf = new RectF(200, 250, 300, 300); // 创建一个矩形
  54. canvas.drawOval(rf, paint); // 画一个椭圆,充满矩形
  55. paint.reset(); // 清除画笔设置
  56. paint.setColor(Color.RED); // 设置画笔颜色
  57. paint.setTextSize(40); // 设置文字大小
  58. paint.setStyle(Style.FILL_AND_STROKE);
  59. canvas.drawText("loading...", 50, 350, paint); // 画一个字符串
  60. }
  61. @Override
  62. public void surfaceCreated(SurfaceHolder holder) // 创建时被调用
  63. {
  64. Canvas canvas = holder.lockCanvas(); // 获取画布
  65. try {
  66. synchronized (holder) {
  67. onDraw(canvas);
  68. } // 绘制
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. } finally {
  72. if (canvas != null) {
  73. holder.unlockCanvasAndPost(canvas);
  74. }
  75. }
  76. }
  77. @Override
  78. public void surfaceDestroyed(SurfaceHolder holder) {
  79. } // 继承方法,空实现
  80. @Override
  81. // 继承方法,空实现
  82. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  83. int height) {
  84. }
  85. }
  86. }

实现的效果是:

2.贴图技术的使用

    贴图技术主要包括图片的移动、旋转、透明度、等变化

下面是关于贴图技术的使用方法  首先是自定义的一个布局

  1. <com.nyist.wj.MysurfaceView
  2. android:id="@+id/mysurfaceview"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent" />

然后就是实现自定义布局引用的类

  1. package com.nyist.wj;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.graphics.Canvas;
  6. import android.graphics.Matrix;
  7. import android.graphics.Paint;
  8. import android.util.AttributeSet;
  9. import android.view.View;
  10. public class MysurfaceView extends View {
  11. Bitmap bitmap;
  12. Paint paint;
  13. public MysurfaceView(Context context,AttributeSet attributeSet) {
  14. super(context,attributeSet);
  15. // TODO Auto-generated constructor stub
  16. this.initBitmap();
  17. }
  18. public void initBitmap() {
  19. // TODO Auto-generated method stub
  20. paint=new Paint();
  21. bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ball);
  22. }
  23. @Override
  24. protected void onDraw(Canvas canvas) {
  25. // TODO Auto-generated method stub
  26. super.onDraw(canvas);
  27. //打开抗锯齿
  28. paint.setAntiAlias(true);
  29. canvas.drawBitmap(bitmap, 50,50,paint);
  30. canvas.save();
  31. Matrix matrix=new Matrix();
  32. //移动
  33. matrix.setTranslate(100, 100);
  34. Matrix matrix2=new Matrix();
  35. // 旋转
  36. matrix2.setRotate(50);
  37. Matrix matrix3=new Matrix();
  38. matrix3.setConcat(matrix, matrix2);
  39. //缩放
  40. matrix.setScale(0.5f, 0.5f);
  41. matrix2.setConcat(matrix3, matrix);
  42. canvas.drawBitmap(bitmap, matrix2, paint);
  43. canvas.restore();
  44. canvas.save();
  45. paint.setAlpha(200);
  46. matrix.setTranslate(150, 150);
  47. //放大
  48. matrix2.setScale(1.3f, 1.3f);
  49. //设置总矩阵
  50. matrix3.setConcat(matrix, matrix2);
  51. canvas.drawBitmap(bitmap, matrix3, paint);
  52. paint.reset();
  53. }
  54. }


实现的效果如下   解释一下:这是横屏显示的结果,左上方是原图片大小  接着是缩放的和放大的图片

3.广告条的实现方法

广告虽不好,但是这确实为android开发者提供了一点微薄的力量,下面就看看广告条的开发

效果图:

实现的过程有自定义的View

  1. <com.nyist.wj.myView
  2. android:layout_width="fill_parent"
  3. android:layout_height="50dip"
  4. />

实现view的方法

  1. package com.nyist.wj;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.content.res.Resources;
  5. import android.graphics.Bitmap;
  6. import android.graphics.BitmapFactory;
  7. import android.graphics.Canvas;
  8. import android.graphics.Matrix;
  9. import android.graphics.Paint;
  10. import android.os.Bundle;
  11. import android.util.AttributeSet;
  12. import android.view.MotionEvent;
  13. import android.view.View;
  14. public class myView extends View {
  15. Bitmap[] bitmap;
  16. int currentindex = 1;
  17. int time = 3000;
  18. boolean isAnima = false;
  19. Paint paint;
  20. int[] imageID;
  21. // 初始化图片数阻
  22. boolean initFlag = false;
  23. float prex, prey;
  24. int xoffset;
  25. public myView(Context context, AttributeSet attributeSet) {
  26. super(context, attributeSet);
  27. // TODO Auto-generated constructor stub
  28. this.imageID = new int[] { R.drawable.test1, R.drawable.test2,
  29. R.drawable.test3, R.drawable.test4 };
  30. // 生成图片数组
  31. bitmap = new Bitmap[imageID.length];
  32. paint = new Paint();
  33. // 抗锯齿
  34. paint.setFlags(Paint.ANTI_ALIAS_FLAG);
  35. this.setOnTouchListener(null);
  36. new Thread() {
  37. public void run() {
  38. while (true) {
  39. if (!isAnima) {
  40. currentindex = (currentindex + 1) % imageID.length;
  41. }
  42. // 刷帧重绘
  43. myView.this.postInvalidate();
  44. try {
  45. Thread.sleep(time);
  46. } catch (Exception e) {
  47. // TODO: handthele exception
  48. }
  49. }
  50. };
  51. }.start();
  52. }
  53. public void initBitmap() {
  54. Resources resources = this.getResources();
  55. for (int i = 0; i < imageID.length; i++) {
  56. // ------------------------------
  57. // 实现图片 的缩放
  58. bitmap[i] = scaleChange(BitmapFactory.decodeResource(resources,
  59. imageID[i]
  60. ));
  61. }
  62. }
  63. public static Bitmap scaleChange(Bitmap bitmap) {
  64. int w = bitmap.getWidth();
  65. int h = bitmap.getHeight();
  66. double xratio = (double) Constant.SCREEN_WIDTH / w;
  67. double yratio = 50.0 / h;
  68. // 生成矩阵
  69. Matrix matrix = new Matrix();
  70. matrix.postScale((float) xratio, (float) yratio);
  71. Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
  72. return result;
  73. }
  74. @Override
  75. public void onDraw(Canvas canvas) {
  76. // TODO Auto-generated method stub
  77. // 第一次运行onDraw方法的时候,调用初始化图片数组的方法
  78. if (!initFlag) {
  79. initBitmap();
  80. initFlag = true;
  81. }
  82. if (canvas == null) {
  83. return;
  84. }
  85. if (!isAnima) {
  86. // -------------------------------------
  87. // 当没有播放动画时候绘制当前图片
  88. drawAD(canvas, xoffset, currentindex);
  89. }
  90. if (isAnima) {
  91. // 当向右滑动时候
  92. if (xoffset > 0) {
  93. int size = imageID.length;
  94. // 得到上一张图片的索引
  95. int preIndex = (currentindex - 1 + size) % size;
  96. // 根据x轴偏移量,算出上一张图片绘制时的x坐标
  97. int nextIndex = xoffset - Constant.SCREEN_WIDTH;
  98. // 绘制当前索引图片
  99. drawAD(canvas, xoffset, (preIndex + 1) % size);
  100. drawAD(canvas, nextIndex, preIndex);
  101. } // 当往左抹时
  102. else if (xoffset < 0) {
  103. int size = imageID.length;
  104. // 得到下一张图片的索引
  105. int preIndex = (currentindex + 1 + size) % size;
  106. int nextIndex = xoffset + Constant.SCREEN_WIDTH;
  107. // 绘制当前图片的索引
  108. drawAD(canvas, xoffset, (preIndex - 1 + size) % size);
  109. drawAD(canvas, nextIndex, preIndex);
  110. }
  111. }
  112. }
  113. public void drawAD(Canvas canvas, int offset, int Index) {
  114. canvas.drawBitmap(bitmap[Index], offset, 0, paint);
  115. }
  116. @Override
  117. public boolean onTouchEvent(MotionEvent event) {
  118. // TODO Auto-generated method stub
  119. float x = event.getX();
  120. float y = event.getY();
  121. switch (event.getAction()) {
  122. case MotionEvent.ACTION_DOWN:
  123. prex = x;
  124. prey = y;
  125. System.out.println("------------------------------------");
  126. System.out.println("+++++++++++++++++++++++++++++++++++"
  127. + currentindex);
  128. return true;
  129. case MotionEvent.ACTION_MOVE:
  130. if (!isAnima && Math.abs(x - prex) > 10) {
  131. isAnima = true;
  132. }
  133. if (isAnima) {
  134. xoffset = (int) (xoffset + x - prex);
  135. prex = x;
  136. prey = y;
  137. }
  138. this.postInvalidate();
  139. return true;
  140. case MotionEvent.ACTION_UP:
  141. if (isAnima) {
  142. if (x < Constant.SCREEN_WIDTH / 4 && xoffset < 0) {
  143. int size = imageID.length;
  144. currentindex = (currentindex + 1) % size;
  145. } else if (x > Constant.SCREEN_WIDTH * 3 / 4 && xoffset > 0) {
  146. int size = imageID.length;
  147. currentindex = (currentindex - 1 + size) % size;
  148. }
  149. }
  150. isAnima = false;
  151. xoffset = 0;
  152. this.postInvalidate();
  153. return true;
  154. }
  155. return false;
  156. }
  157. }


接着是在activity中的插入

  1. package com.nyist.wj;
  2. import android.app.Activity;
  3. import android.content.pm.ActivityInfo;
  4. import android.os.Bundle;
  5. import android.util.DisplayMetrics;
  6. import android.view.Window;
  7. import android.view.WindowManager;
  8. public class GuangGaoActivity extends Activity {
  9. /** Called when the activity is first created. */
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. requestWindowFeature(Window.FEATURE_NO_TITLE);
  14. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
  15. // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  16. setContentView(R.layout.main);
  17. DisplayMetrics displayMetrics=new DisplayMetrics();
  18. getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
  19. Constant.SCREEN_HEIGHT=displayMetrics.heightPixels; //获取具体的屏幕分辨率数值
  20. Constant.SCREEN_WIDTH=displayMetrics.widthPixels;
  21. }
  22. }

 

4.下面是介绍2D下简单的游戏开发

效果图如下

主要用到的SurfaceView 和贴图技术以及声音的处理

用到的处理方法共有5个类

1.BallGameActivity                        设置屏幕的相关属性

2.GameSurfaceView                    实现显示界面的设置

3.ThreadForDraw                       刷帧线程重新绘制游戏界面

4.ThreadForGo                            控制小球移动

5.ThreadForTimecControl         计算小球运行的时间

下面分别介绍每个类是如何实现的

1.BallGameActivity

  1. package com.nyist.wj;
  2. import java.util.HashMap;
  3. import org.apache.http.auth.AUTH;
  4. import android.app.Activity;
  5. import android.content.Context;
  6. import android.media.AudioManager;
  7. import android.media.SoundPool;
  8. import android.os.Bundle;
  9. import android.view.Window;
  10. import android.view.WindowManager;
  11. public class BallGameActivity extends Activity {
  12. GameSurfaceView gameSurfaceView;
  13. // 声音缓冲池
  14. SoundPool soundPool;
  15. // 存放声音ID的 map
  16. HashMap<Integer, Integer> soundpoolMap;
  17. /** Called when the activity is first created. */
  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. // 初始化声音
  22. initSounds();
  23. // 设置全屏
  24. requestWindowFeature(Window.FEATURE_NO_TITLE);
  25. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  26. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  27. gameSurfaceView = new GameSurfaceView(this);
  28. setContentView(gameSurfaceView);
  29. // 循环播放音乐
  30. playSound(1, -1);
  31. }
  32. public void playSound(int sound, int loop) {
  33. // TODO Auto-generated method stub
  34. // 播放声音的方法
  35. AudioManager audioManager = (AudioManager) this
  36. .getSystemService(Context.AUDIO_SERVICE);
  37. float streamVolumeMax = audioManager
  38. .getStreamMaxVolume(audioManager.STREAM_MUSIC);
  39. float streamVolumeCurrent = audioManager
  40. .getStreamVolume(AudioManager.STREAM_MUSIC);
  41. float volume = streamVolumeCurrent / streamVolumeMax;
  42. // 参数 声音资源的ID 左声道 右声道 优先级 循环次数 回访速度
  43. soundPool.play(soundpoolMap.get(sound), volume, volume, 1, loop, 0.5f);
  44. }
  45. public void initSounds() {
  46. // TODO Auto-generated method stub
  47. // 参数 播放的个数 音频类型 播放的质量
  48. soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
  49. // 创建声音资源的MAP
  50. soundpoolMap = new HashMap<Integer, Integer>();
  51. // 将加载声音的资源 放在map中
  52. soundpoolMap.put(1, soundPool.load(this, R.raw.bg, 1));
  53. }
  54. }


 

2.GameSurfaceView

  1. package com.nyist.wj;
  2. import android.graphics.Bitmap;
  3. import android.graphics.BitmapFactory;
  4. import android.graphics.Canvas;
  5. import android.view.MotionEvent;
  6. import android.view.SurfaceHolder;
  7. import android.view.SurfaceView;
  8. public class GameSurfaceView extends SurfaceView implements
  9. SurfaceHolder.Callback {
  10. BallGameActivity ballGameActivity;
  11. ThreadForTimecControl threadForTimecControl;
  12. ThreadForGo threadForGo;
  13. ThreadForDraw threadForDraw;
  14. int backSize = 16; // 背景块大小
  15. int screenWidth = 320; // 屏幕宽度
  16. int screenHeight = 480; // 屏幕高度
  17. int bannerWidth = 40; // 挡板宽度
  18. int bannerHeight = 6; // 挡板高度
  19. int bottomSpance = 16; // 下端留白
  20. int bannerSpan = 5; // 板每次移动的距离
  21. int ballSpan = 8; // 球每次移动的距离
  22. int ballSize = 16; // 小球大小
  23. int hintWidth = 100; // 游戏说明宽度
  24. int hintHeight = 20; // 游戏说明高度
  25. int status = 0; // 游戏状态控制 0-等待开始 1-进行中 2-游戏结束 3-游戏胜利
  26. int score = 0; // 得分
  27. int ballx; // 小球x坐标
  28. int bally; // 小球y坐标
  29. int direction = 0; // 小球方向
  30. int bannerX; // 挡板X坐标
  31. int bannerY; // 挡板Y坐标
  32. int scoreWidth = 32;
  33. Bitmap iback; // 背景图
  34. Bitmap[] iscore = new Bitmap[10];// 得分图
  35. Bitmap iball; // 小球用图
  36. Bitmap ibanner; // 挡板用图
  37. Bitmap ibegin; // 开始用图
  38. Bitmap igameover; // 游戏结束用图
  39. Bitmap iwin; // 游戏结束用图
  40. Bitmap iexit; // 退出用图
  41. Bitmap ireplay; // 重玩用图
  42. public GameSurfaceView(BallGameActivity ballGameActivity) {
  43. super(ballGameActivity);
  44. // 注册回调接口
  45. getHolder().addCallback(this);
  46. this.ballGameActivity = ballGameActivity;
  47. initBitmap();
  48. // /----------------------------------------------
  49. threadForDraw = new ThreadForDraw(this);
  50. // TODO Auto-generated constructor stub
  51. }
  52. public void initBitmap() {
  53. iback = BitmapFactory.decodeResource(getResources(), R.drawable.back);
  54. iscore[0] = BitmapFactory.decodeResource(getResources(), R.drawable.d0);
  55. iscore[1] = BitmapFactory.decodeResource(getResources(), R.drawable.d1);
  56. iscore[2] = BitmapFactory.decodeResource(getResources(), R.drawable.d2);
  57. iscore[3] = BitmapFactory.decodeResource(getResources(), R.drawable.d3);
  58. iscore[4] = BitmapFactory.decodeResource(getResources(), R.drawable.d4);
  59. iscore[5] = BitmapFactory.decodeResource(getResources(), R.drawable.d5);
  60. iscore[6] = BitmapFactory.decodeResource(getResources(), R.drawable.d6);
  61. iscore[7] = BitmapFactory.decodeResource(getResources(), R.drawable.d7);
  62. iscore[8] = BitmapFactory.decodeResource(getResources(), R.drawable.d8);
  63. iscore[9] = BitmapFactory.decodeResource(getResources(), R.drawable.d9);
  64. iball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
  65. ibanner = BitmapFactory.decodeResource(getResources(),
  66. R.drawable.banner);
  67. ibegin = BitmapFactory.decodeResource(getResources(), R.drawable.begin);
  68. igameover = BitmapFactory.decodeResource(getResources(),
  69. R.drawable.gameover);
  70. iwin = BitmapFactory.decodeResource(getResources(), R.drawable.win);
  71. iexit = BitmapFactory.decodeResource(getResources(), R.drawable.exit);
  72. ireplay = BitmapFactory.decodeResource(getResources(),
  73. R.drawable.replay);
  74. // 初始化小球位置及板X坐标
  75. initBallAndBanner();
  76. }
  77. public void initBallAndBanner() {
  78. // 初始化小球位置
  79. bally = screenHeight - bottomSpance - bannerHeight - ballSize;
  80. ballx = screenWidth / 2 - ballSize / 2;
  81. // 初始化板X坐标
  82. bannerX = screenWidth / 2 - bannerWidth / 2;
  83. bannerY = screenHeight - bottomSpance - bannerHeight;
  84. }
  85. public void replay() {
  86. if (status == 2 || status == 3) {
  87. // 初始化小球的位置
  88. initBallAndBanner();
  89. score = 0;
  90. status = 0;
  91. direction = 3;
  92. }
  93. }
  94. @Override
  95. protected void onDraw(Canvas canvas) {
  96. // TODO Auto-generated method stub
  97. super.onDraw(canvas);
  98. // 清除背景
  99. int colum = screenWidth / backSize
  100. + ((scoreWidth % backSize == 0) ?0:1);
  101. int rows = screenHeight / backSize
  102. + ((screenHeight % backSize == 0) ? 0 : 1);
  103. for (int i = 0; i < rows; i++) {
  104. for (int j = 0; j < colum; j++) {
  105. canvas.drawBitmap(iback, 16*j, 16*i, null);
  106. }
  107. }
  108. // 绘制得分
  109. String scorestr = score + "";
  110. int loop = 3 - scorestr.length();
  111. for (int i = 0; i < loop; i++) {
  112. scorestr = "0" + scorestr;
  113. }
  114. int startX = screenWidth - scoreWidth * 3 - 10;
  115. for (int i = 0; i < 3; i++) {
  116. int tempScore = scorestr.charAt(i) - '0';
  117. canvas.drawBitmap(iscore[tempScore], startX + i * scoreWidth, 5,
  118. null);
  119. }
  120. // 绘制小球
  121. canvas.drawBitmap(iball, ballx, bally, null);
  122. // 绘制板
  123. canvas.drawBitmap(ibanner, bannerX, bannerY, null);
  124. // 绘制开始提示
  125. if (status == 0) {
  126. canvas.drawBitmap(ibegin, screenWidth / 2 - hintWidth / 2,
  127. screenHeight / 2 - hintHeight / 2, null);
  128. }
  129. // 绘制失败提示
  130. if (status == 2) {
  131. canvas.drawBitmap(igameover, screenWidth / 2 - hintWidth / 2,
  132. screenHeight / 2 - hintHeight / 2, null);
  133. }
  134. // 绘制胜利提示
  135. if (status == 3) {
  136. canvas.drawBitmap(iwin, screenWidth / 2 - hintWidth / 2,
  137. screenHeight / 2 - hintHeight / 2, null);
  138. }
  139. // 绘制退出提示
  140. canvas.drawBitmap(iexit, screenWidth - 32, screenHeight - 16, null);
  141. // /绘制重玩提示
  142. if (status == 2 || status == 3) {
  143. canvas.drawBitmap(ireplay, 0, screenHeight - 16, null);
  144. }
  145. }
  146. @Override
  147. public boolean onTouchEvent(MotionEvent event) {
  148. int x = (int) event.getX();
  149. int y = (int) event.getY();
  150. if (x < screenWidth && x > screenWidth - 32 && y < screenHeight
  151. && y > screenHeight - 16) {
  152. // ----------------------------------------------------------
  153. // 按下退出选项退出系统
  154. ballGameActivity.soundPool.stop(1);
  155. System.exit(0);
  156. }
  157. // 等待状态
  158. if (status == 0) {
  159. status = 1;
  160. // ----------------------------------------------
  161. threadForTimecControl = new ThreadForTimecControl(this);
  162. threadForGo = new ThreadForGo(this);
  163. threadForTimecControl.start();
  164. threadForGo.start();
  165. } else if (status == 1) {
  166. bannerX = x;
  167. } else if (status == 2 || status == 3) {
  168. if (x < 32 && x > 0 && y < screenHeight && y > screenHeight - 16) {
  169. //按下重玩
  170. replay();
  171. }
  172. }
  173. // TODO Auto-generated method stub
  174. return super.onTouchEvent(event);
  175. }
  176. @Override
  177. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  178. int height) {
  179. // TODO Auto-generated method stub
  180. }
  181. @Override
  182. public void surfaceCreated(SurfaceHolder holder) {
  183. // TODO Auto-generated method stub
  184. // ----------------------------------
  185. // 创建时候启动相关进程
  186. this.threadForDraw.flag = true;
  187. threadForDraw.start();
  188. }
  189. @Override
  190. public void surfaceDestroyed(SurfaceHolder holder) {
  191. // 释放相应的进程
  192. boolean retry = true;
  193. this.threadForDraw.flag = false;
  194. // 不断的循环知道刷帧结束
  195. while (retry) {
  196. try {
  197. threadForDraw.join();
  198. retry = false;
  199. } catch (InterruptedException e) {
  200. // TODO: handle exception
  201. }
  202. }
  203. }
  204. }


 

3.ThreadForDraw

  1. package com.nyist.wj;
  2. import android.graphics.Canvas;
  3. import android.view.SurfaceHolder;
  4. public class ThreadForDraw extends Thread {
  5. boolean flag=true;
  6. int sleep=100;
  7. GameSurfaceView gameSurfaceView;
  8. SurfaceHolder surfaceHolder;
  9. public ThreadForDraw (GameSurfaceView gameSurfaceView){
  10. this.gameSurfaceView=gameSurfaceView;
  11. this.surfaceHolder=gameSurfaceView.getHolder();
  12. }
  13. @Override
  14. public void run() {
  15. // TODO Auto-generated method stub
  16. Canvas canvas;
  17. while (this.flag) {
  18. canvas=null;
  19. try {
  20. canvas=this.surfaceHolder.lockCanvas(null);
  21. synchronized (this.surfaceHolder) {
  22. gameSurfaceView.onDraw(canvas);
  23. }
  24. } catch (Exception e) {
  25. }finally{
  26. if (canvas!=null) {
  27. this.surfaceHolder.unlockCanvasAndPost(canvas);
  28. }
  29. }
  30. try {
  31. Thread.sleep(sleep);
  32. } catch (Exception e) {
  33. // TODO: handle exception
  34. }
  35. }
  36. super.run();
  37. }
  38. }


 

4.ThreadForGo

  1. package com.nyist.wj;
  2. //游戏过程中移动小球的线程
  3. public class ThreadForGo extends Thread {
  4. // 设置线程执行的标志
  5. boolean flag = true;
  6. // 游戏界面的引用
  7. GameSurfaceView gameSurfaceView;
  8. public ThreadForGo(GameSurfaceView gameSurfaceView) {
  9. this.gameSurfaceView = gameSurfaceView;
  10. }
  11. @Override
  12. public void run() {
  13. // TODO Auto-generated method stub
  14. while (flag) {
  15. switch (gameSurfaceView.direction) {
  16. case 0:
  17. // 右上控制当前方向移动球
  18. gameSurfaceView.ballx = gameSurfaceView.ballx
  19. + gameSurfaceView.ballSpan;
  20. gameSurfaceView.bally = gameSurfaceView.bally
  21. - gameSurfaceView.ballSpan;
  22. // 判断是否碰壁
  23. if (gameSurfaceView.ballx >= gameSurfaceView.screenWidth
  24. - gameSurfaceView.ballSize) {
  25. // 碰到上壁
  26. gameSurfaceView.direction = 3;
  27. } else if (gameSurfaceView.bally <= 0) {
  28. gameSurfaceView.direction = 1;
  29. }
  30. break;
  31. case 1:
  32. // 右下
  33. gameSurfaceView.ballx = gameSurfaceView.ballx
  34. + gameSurfaceView.ballSpan;
  35. gameSurfaceView.bally = gameSurfaceView.bally
  36. + gameSurfaceView.ballSpan;
  37. // 碰到下壁
  38. if (gameSurfaceView.bally >= gameSurfaceView.screenHeight
  39. - gameSurfaceView.bannerHeight
  40. - gameSurfaceView.bottomSpance
  41. - gameSurfaceView.ballSize) {
  42. // /-----------------------------------------
  43. checkCollision(1);
  44. // 碰到右臂
  45. } else if (gameSurfaceView.ballx >= gameSurfaceView.screenWidth
  46. - gameSurfaceView.ballSize) {
  47. gameSurfaceView.direction = 2;
  48. }
  49. break;
  50. case 2:
  51. // 左下
  52. gameSurfaceView.ballx = gameSurfaceView.ballx
  53. - gameSurfaceView.ballSpan;
  54. gameSurfaceView.bally = gameSurfaceView.bally
  55. + gameSurfaceView.ballSpan;
  56. // 碰到下壁
  57. if (gameSurfaceView.bally >= gameSurfaceView.screenHeight
  58. - gameSurfaceView.bannerHeight
  59. - gameSurfaceView.bottomSpance
  60. - gameSurfaceView.ballSize) {
  61. // -----------------------------------
  62. checkCollision(2);
  63. }
  64. // 碰到左壁
  65. else if (gameSurfaceView.ballx <= 0) {
  66. gameSurfaceView.direction = 1;
  67. }
  68. break;
  69. case 3:
  70. gameSurfaceView.ballx = gameSurfaceView.ballx
  71. - gameSurfaceView.ballSpan;
  72. gameSurfaceView.bally = gameSurfaceView.bally
  73. - gameSurfaceView.ballSpan;
  74. // /碰到左壁
  75. if (gameSurfaceView.ballx <= 0) {
  76. gameSurfaceView.direction = 0;
  77. }
  78. // 碰到上壁
  79. else if (gameSurfaceView.bally <= 0) {
  80. gameSurfaceView.direction = 2;
  81. }
  82. break;
  83. default:
  84. break;
  85. }
  86. try {
  87. Thread.sleep(100);
  88. } catch (Exception e) {
  89. // TODO: handle exception
  90. }
  91. }
  92. }
  93. public void checkCollision(int dirction) {
  94. if (gameSurfaceView.ballx >= gameSurfaceView.bannerX
  95. - gameSurfaceView.ballSize
  96. && gameSurfaceView.ballx <= gameSurfaceView.bannerX
  97. + gameSurfaceView.bannerWidth) {
  98. switch (dirction) {
  99. case 1:
  100. gameSurfaceView.direction = 0;
  101. break;
  102. case 2:
  103. gameSurfaceView.direction = 3;
  104. break;
  105. default:
  106. break;
  107. }
  108. } else {
  109. // 没有碰到板
  110. gameSurfaceView.threadForTimecControl.flag = false;
  111. gameSurfaceView.threadForGo.flag = false;
  112. gameSurfaceView.status = 2;
  113. }
  114. }
  115. }


 

 

 5.ThreadForTimecControl

 

  1. package com.nyist.wj;
  2. public class ThreadForTimecControl extends Thread {
  3. //计算生存时间的线程
  4. //判断是否胜利的值
  5. int highest = 200;
  6. // 游戏界面的引入
  7. GameSurfaceView gameSurfaceView;
  8. //线程标志位
  9. boolean flag = true;
  10. public ThreadForTimecControl(GameSurfaceView gameSurfaceView) {
  11. this.gameSurfaceView = gameSurfaceView;
  12. }
  13. @Override
  14. public void run() {
  15. // TODO Auto-generated method stub
  16. while(flag){
  17. gameSurfaceView.score++;
  18. if (gameSurfaceView.score==highest) {
  19. //游戏胜利
  20. gameSurfaceView.status=3;
  21. //----------------------------------------
  22. gameSurfaceView.threadForTimecControl.flag=false;
  23. gameSurfaceView.threadForGo.flag=false;
  24. }
  25. try {
  26. Thread.sleep(1000);
  27. } catch (Exception e) {
  28. // TODO: handle exception
  29. }
  30. }
  31. }
  32. }



 

ps:个人总结

小球的初始位置确定

代码是

  1. // 初始化小球位置
  2. bally = screenHeight - bottomSpance - bannerHeight - ballSize;
  3. ballx = screenWidth / 2 - ballSize / 2;
  4. // 初始化板X坐标
  5. bannerX = screenWidth / 2 - bannerWidth / 2;
  6. bannerY = screenHeight - bottomSpance - bannerHeight;


 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/132918
推荐阅读
相关标签
  

闽ICP备14008679号