Android实现疯狂连连看游戏之加载界面图片和实现游戏Activity(四)

Android实现疯狂连连看游戏之加载界面图片和实现游戏Activity(四),第1张

概述正如在《我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)》一文中看到的,在AbstractBoard的代码中,当程序需要创建N个Piece对象时,程序会直接调用ImageUtil的getPlayImages()方法去获

正如在《我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)》一文中看到的,在AbstractBoard的代码中,当程序需要创建N个PIEce对象时,程序会直接调用ImageUtil的getPlayImages()方法去获取图片,该方法会随机从res/drawable目录中取得N张图片。

下面是res/drawable目录视图:

为了让getPlayImages()方法能随机从res/drawable目录中取得N张图片,具体实现分为以下几步:

通过反射来获取R.drawable的所有FIEld(AndroID的每张图片资源都会自动转换为R.drawable的静态FIEld),并将这些FIEld值添加到一个List集合中。 从第一步得到的List集合中随机“抽取”N/2个图片ID。 将第二步得到的N/2个图片ID全部复制一份,这样就得到了N个图片ID,而且每个图片ID都可以找到与之配对的。 将第三步得到的N个图片ID再次“随机打乱”,并根据图片ID加载相应的Bitmap对象,最后把图片ID及对应的Bitmap封装成PIEceImage对象后返回。

下面是ImageUtil类的代码:cn\oyp\link\utils\ImageUtil.java

package cn.oyp.link.utils;  import java.lang.reflect.FIEld; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random;  import androID.content.Context; import androID.graphics.Bitmap; import androID.graphics.BitmapFactory; import cn.oyp.link.R; import cn.oyp.link.vIEw.PIEceImage;  /**  * 图片资源工具类,主要用于读取游戏图片资源值<br/>  * <br/>  * 关于本代码介绍可以参考一下博客: <a href="http://blog.csdn.net/ouyang_peng" rel="external nofollow" rel="external nofollow" >欧阳鹏的CSDN博客</a> <br/>  */ public class ImageUtil {  /**   * 保存所有连连看图片资源值(int类型)   */  private static List<Integer> imageValues = getimageValues();   /**   * 获取连连看所有图片的ID(约定所有图片ID以p_开头)   */  public static List<Integer> getimageValues() {   try {    // 得到R.drawable所有的属性,即获取drawable目录下的所有图片    FIEld[] drawableFIElds = R.drawable.class.getFIElds();    List<Integer> resourceValues = new ArrayList<Integer>();    for (FIEld fIEld : drawableFIElds) {     // 如果该FIEld的名称以p_开头     if (fIEld.getname().indexOf("p_") != -1) {      resourceValues.add(fIEld.getInt(R.drawable.class));     }    }    return resourceValues;   } catch (Exception e) {    return null;   }  }   /**   * 随机从sourceValues的集合中获取size个图片ID,返回结果为图片ID的集合   *   * @param sourceValues   *   从中获取的集合   * @param size   *   需要获取的个数   * @return size个图片ID的集合   */  public static List<Integer> getRandomValues(List<Integer> sourceValues,int size) {   // 创建一个随机数生成器   Random random = new Random();   // 创建结果集合   List<Integer> result = new ArrayList<Integer>();   for (int i = 0; i < size; i++) {    try {     // 随机获取一个数字,大于、小于sourceValues.size()的数值     int index = random.nextInt(sourceValues.size());     // 从图片ID集合中获取该图片对象     Integer image = sourceValues.get(index);     // 添加到结果集中     result.add(image);    } catch (indexoutofboundsexception e) {     return result;    }   }   return result;  }   /**   * 从drawable目录中中获取size个图片资源ID(以p_为前缀的资源名称),其中size为游戏数量   *   * @param size   *   需要获取的图片ID的数量   * @return size个图片ID的集合   */  public static List<Integer> getPlayValues(int size) {   if (size % 2 != 0) {    // 如果该数除2有余数,将size加1    size += 1;   }   // 再从所有的图片值中随机获取size的一半数量,即N/2张图片   List<Integer> playImageValues = getRandomValues(imageValues,size / 2);   // 将playImageValues集合的元素增加一倍(保证所有图片都有与之配对的图片),即N张图片   playImageValues.addAll(playImageValues);   // 将所有图片ID随机“洗牌”   Collections.shuffle(playImageValues);   return playImageValues;  }   /**   * 将图片ID集合转换PIEceImage对象集合,PIEceImage封装了图片ID与图片本身   *   * @param context   * @param resourceValues   * @return size个PIEceImage对象的集合   */  public static List<PIEceImage> getPlayImages(Context context,int size) {   // 获取图片ID组成的集合   List<Integer> resourceValues = getPlayValues(size);   List<PIEceImage> result = new ArrayList<PIEceImage>();   // 遍历每个图片ID   for (Integer value : resourceValues) {    // 加载图片    Bitmap bm = BitmapFactory.decodeResource(context.getResources(),value);    // 封装图片ID与图片本身    PIEceImage pIEceImage = new PIEceImage(bm,value);    result.add(pIEceImage);   }   return result;  }   /**   * 获取选中标识的图片   * @param context   * @return 选中标识的图片   */  public static Bitmap getSelectimage(Context context) {   Bitmap bm = BitmapFactory.decodeResource(context.getResources(),R.drawable.selected);   return bm;  } } 

前面已经给出了游戏界面的布局文件,该布局文件需要一个Activity来负责显示,除此之外,Activity还需要为游戏界面的按钮、GameVIEw组件的事件提供事件监听器。
尤其是对于GameVIEw组件,程序需要监听用户的触摸动作,当用户触摸屏幕时,程序需要获取用户触摸的是哪个方块,并判断是否需要“消除”该方块。为了判断是否消除该方块,程序需要进行如下判断:

如果程序之前已经选择了某个方块,就判断当前触碰的方块是否能和之前的方块“相连”,如果可以相连,则消除两个方块;如果不能相连,则把当前方块设置为选中方块。

如果程序之前没有选中方块,直接将当前方块设置为选中方块。

下面是Activity的代码:cn\oyp\link\linkActivity.java

package cn.oyp.link;  import java.util.Timer; import java.util.TimerTask;  import androID.app.Activity; import androID.app.AlertDialog; import androID.content.DialogInterface; import androID.os.Bundle; import androID.os.Handler; import androID.os.Message; import androID.os.Vibrator; import androID.vIEw.MotionEvent; import androID.vIEw.VIEw; import androID.Widget.button; import androID.Widget.TextVIEw; import cn.oyp.link.board.GameService; import cn.oyp.link.board.impl.GameServiceImpl; import cn.oyp.link.utils.GameConf; import cn.oyp.link.utils.linkInfo; import cn.oyp.link.vIEw.GameVIEw; import cn.oyp.link.vIEw.PIEce;  /**  * 游戏Activity <br/>  * <br/>  * 关于本代码介绍可以参考一下博客: <a href="http://blog.csdn.net/ouyang_peng" rel="external nofollow" rel="external nofollow" >欧阳鹏的CSDN博客</a> <br/>  */ public class linkActivity extends Activity {  /**   * 游戏配置对象   */  private GameConf config;  /**   * 游戏业务逻辑接口   */  private GameService gameService;  /**   * 游戏界面   */  private GameVIEw gameVIEw;  /**   * 开始按钮   */  private button startbutton;  /**   * 记录剩余时间的TextVIEw   */  private TextVIEw timeTextVIEw;  /**   * 失败后d出的对话框   */  private AlertDialog.Builder lostDialog;  /**   * 游戏胜利后的对话框   */  private AlertDialog.Builder successDialog;  /**   * 定时器   */  private Timer timer = new Timer();  /**   * 记录游戏的剩余时间   */  private int gameTime;  /**   * 记录是否处于游戏状态   */  private boolean isPlaying;  /**   * 振动处理类   */  private Vibrator vibrator;  /**   * 记录已经选中的方块   */  private PIEce selectedPIEce = null;  /**   * Handler类,异步处理   */  private Handler handler = new Handler() {   public voID handleMessage(Message msg) {    switch (msg.what) {    case 0x123:     timeTextVIEw.setText("剩余时间: " + gameTime);     gameTime--; // 游戏剩余时间减少     // 时间小于0,游戏失败     if (gameTime < 0) {      // 停止计时      stopTimer();      // 更改游戏的状态      isPlaying = false;      // 失败后d出对话框      lostDialog.show();      return;     }     break;    }   }  };   @OverrIDe  public voID onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentVIEw(R.layout.main);   // 初始化界面   init();  }   /**   * 初始化游戏的方法   */  private voID init() {   config = new GameConf(8,9,2,10,GameConf.DEFAulT_TIME,this);   // 得到游戏区域对象   gameVIEw = (GameVIEw) findVIEwByID(R.ID.gameVIEw);   // 获取显示剩余时间的文本框   timeTextVIEw = (TextVIEw) findVIEwByID(R.ID.timeText);   // 获取开始按钮   startbutton = (button) this.findVIEwByID(R.ID.startbutton);   // 获取振动器   vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);   // 初始化游戏业务逻辑接口   gameService = new GameServiceImpl(this.config);   // 设置游戏逻辑的实现类   gameVIEw.setGameService(gameService);   // 为开始按钮的单击事件绑定事件监听器   startbutton.setonClickListener(new VIEw.OnClickListener() {    @OverrIDe    public voID onClick(VIEw source) {     startGame(GameConf.DEFAulT_TIME);    }   });   // 为游戏区域的触碰事件绑定监听器   this.gameVIEw.setontouchListener(new VIEw.OntouchListener() {    public boolean ontouch(VIEw vIEw,MotionEvent e) {     if (e.getAction() == MotionEvent.ACTION_DOWN) {      gameVIEwtouchDown(e);     }     if (e.getAction() == MotionEvent.ACTION_UP) {      gameVIEwtouchUp(e);     }     return true;    }   });   // 初始化游戏失败的对话框   lostDialog = createDialog("Lost","游戏失败! 重新开始",R.drawable.lost)     .setPositivebutton("确定",new DialogInterface.OnClickListener() {      public voID onClick(DialogInterface dialog,int which) {       startGame(GameConf.DEFAulT_TIME);      }     });   // 初始化游戏胜利的对话框   successDialog = createDialog("Success","游戏胜利! 重新开始",R.drawable.success).setPositivebutton("确定",int which) {       startGame(GameConf.DEFAulT_TIME);      }     });  }   @OverrIDe  protected voID onPause() {   // 暂停游戏   stopTimer();   super.onPause();  }   @OverrIDe  protected voID onResume() {   // 如果处于游戏状态中   if (isPlaying) {    // 以剩余时间重新开始游戏    startGame(gameTime);   }   super.onResume();  }   /**   * 触碰游戏区域的处理方法   *   * @param event   */  private voID gameVIEwtouchDown(MotionEvent event) {   // 获取GameServiceImpl中的PIEce[][]数组   PIEce[][] pIEces = gameService.getPIEces();   // 获取用户点击的x座标   float touchX = event.getX();   // 获取用户点击的y座标   float touchY = event.getY();   // 根据用户触碰的座标得到对应的PIEce对象   PIEce currentPIEce = gameService.findPIEce(touchX,touchY);   // 如果没有选中任何PIEce对象(即鼠标点击的地方没有图片),不再往下执行   if (currentPIEce == null)    return;   // 将gameVIEw中的选中方块设为当前方块   this.gameVIEw.setSelectedPIEce(currentPIEce);   // 表示之前没有选中任何一个PIEce   if (this.selectedPIEce == null) {    // 将当前方块设为已选中的方块,重新将GamePanel绘制,并不再往下执行    this.selectedPIEce = currentPIEce;    this.gameVIEw.postInvalIDate();    return;   }   // 表示之前已经选择了一个   if (this.selectedPIEce != null) {    // 在这里就要对currentPIEce和prePIEce进行判断并进行连接    linkInfo linkInfo = this.gameService.link(this.selectedPIEce,currentPIEce);    // 两个PIEce不可连,linkInfo为null    if (linkInfo == null) {     // 如果连接不成功,将当前方块设为选中方块     this.selectedPIEce = currentPIEce;     this.gameVIEw.postInvalIDate();    } else {     // 处理成功连接     handleSuccesslink(linkInfo,this.selectedPIEce,currentPIEce,pIEces);    }   }  }   /**   * 触碰游戏区域的处理方法   *   * @param e   */  private voID gameVIEwtouchUp(MotionEvent e) {   this.gameVIEw.postInvalIDate();  }   /**   * 以gameTime作为剩余时间开始或恢复游戏   *   * @param gameTime   *   剩余时间   */  private voID startGame(int gameTime) {   // 如果之前的timer还未取消,取消timer   if (this.timer != null) {    stopTimer();   }   // 重新设置游戏时间   this.gameTime = gameTime;   // 如果游戏剩余时间与总游戏时间相等,即为重新开始新游戏   if (gameTime == GameConf.DEFAulT_TIME) {    // 开始新的游戏游戏    gameVIEw.startGame();   }   isPlaying = true;   this.timer = new Timer();   // 启动计时器 , 每隔1秒发送一次消息   this.timer.schedule(new TimerTask() {    public voID run() {     handler.sendEmptyMessage(0x123);    }   },1000);   // 将选中方块设为null。   this.selectedPIEce = null;  }   /**   * 成功连接后处理   *   * @param linkInfo   *   连接信息   * @param prePIEce   *   前一个选中方块   * @param currentPIEce   *   当前选择方块   * @param pIEces   *   系统中还剩的全部方块   */  private voID handleSuccesslink(linkInfo linkInfo,PIEce prePIEce,PIEce currentPIEce,PIEce[][] pIEces) {   // 它们可以相连,让GamePanel处理linkInfo   this.gameVIEw.setlinkInfo(linkInfo);   // 将gameVIEw中的选中方块设为null   this.gameVIEw.setSelectedPIEce(null);   this.gameVIEw.postInvalIDate();   // 将两个PIEce对象从数组中删除   pIEces[prePIEce.getIndexX()][prePIEce.getIndexY()] = null;   pIEces[currentPIEce.getIndexX()][currentPIEce.getIndexY()] = null;   // 将选中的方块设置null。   this.selectedPIEce = null;   // 手机振动(100毫秒)   this.vibrator.vibrate(100);   // 判断是否还有剩下的方块,如果没有,游戏胜利   if (!this.gameService.hasPIEces()) {    // 游戏胜利    this.successDialog.show();    // 停止定时器    stopTimer();    // 更改游戏状态    isPlaying = false;   }  }   /**   * 创建对话框的工具方法   *   * @param Title   *   标题   * @param message   *   内容   * @param imageResource   *   图片   * @return   */  private AlertDialog.Builder createDialog(String Title,String message,int imageResource) {   return new AlertDialog.Builder(this).setTitle(Title)     .setMessage(message).setIcon(imageResource);  }   /**   * 停止计时   */  private voID stopTimer() {   // 停止定时器   this.timer.cancel();   this.timer = null;  } } 

该Activity用了两个类,这两个类在下一篇博客中再进行相关描述。
GameConf:负责管理游戏的初始化设置信息。
GameService:负责游戏的逻辑实现。

关于具体的实现步骤,请参考下面的链接:

我的Android进阶之旅------>Android疯狂连连看游戏的实现之游戏效果预览(一)

我的Android进阶之旅------>Android疯狂连连看游戏的实现之开发游戏界面(二)

我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)

我的Android进阶之旅------>Android疯狂连连看游戏的实现之实现游戏逻辑(五)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android实现疯狂连连看游戏之加载界面图片和实现游戏Activity(四)全部内容,希望文章能够帮你解决Android实现疯狂连连看游戏之加载界面图片和实现游戏Activity(四)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1146478.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存