在别人基础改写贪吃蛇代码

原来的贪吃蛇是在模拟机上运行的,需要按键去操控,而我呢,就是改写在真机上运行的,用手指滑动控制

改写代码就是把原来的onkey()改为ontoucheven()

代码如下

   @Override
    public boolean onTouchEvent(MotionEvent e) {
    // TODO Auto-generated method stub
    switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
startPoint.x = (int) e.getX();
startPoint.y = (int) e.getY();
break;

case MotionEvent.ACTION_UP:
endPoint.x = (int) e.getX();
endPoint.y = (int) e.getY();
actionCheck();
break;
    }


return true;
   
    }



public void actionCheck(){
    //手指向上滑动
    if (startPoint.y >endPoint.y && Math.abs(startPoint.y-endPoint.y)>Math.abs(startPoint.x-endPoint.x)) {
if (mMode == READY | mMode == LOSE) {
           /*
            * At the beginning of the game, or the end of a previous one,
            * we should start a new game.
            */
           initNewGame();
           setMode(RUNNING);
           update(); //update()实现了对游戏数据的更新,是整个游戏的推动力。
       }
if (mMode == PAUSE) {
           /*
            * If the game is merely paused, we should just continue where
            * we left off.
            */
           setMode(RUNNING);
           update();
       } 


           if (mDirection != SOUTH) {  //如果按键的方向 跟蛇本身的运动方向完全相反,则无法执行
               mNextDirection = NORTH;  
           }
}

//手指向下滑动
if (startPoint.y <endPoint.y && Math.abs(startPoint.y-endPoint.y)>Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != NORTH) {
              mNextDirection = SOUTH;
          }
}

//手指向左滑动
if (startPoint.x >endPoint.x && Math.abs(startPoint.y-endPoint.y)<Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != EAST) {
              mNextDirection = WEST;
          }
}

//手指向右滑动
if (startPoint.x <endPoint.x && Math.abs(startPoint.y-endPoint.y)<Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != WEST) {
              mNextDirection = EAST;
          }
}



一开始我想应该是用实现监听接口的方法来实现控制,但是却无法导入包,上网找也找不到原因所在,后来才用当前的办法来解决

还有就是,startpoint 和endpoint没有实例化,出现了NPE异常

我只是菜鸟,还要继续努力

下一步,实现用重力感应来操控

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章