Translate

четверг, 24 мая 2012 г.

Android programming for beginners. "Hangman" the word game developing for android. Touch event

 Continue to make game for android. Previous part

 Today we will learn about how to obtain and handle touch event. If user touch the screen, we must determine the letter under his/her finger. It's math via touch coordinates.





 If there is not picked letter in the word, we will add one to the wrong letter string and mark this. Analogically with right letters.

Because we have not wrote code for drawing word and lives on the screen yet, we write code for letter determining and call unwritten checkLetter method.

 Make onTouchEvent method in custom component class for obtaining and handle screen touch. There is one parameter of this method - the event. Its contain important propertries for touch mining - coordinates of touch point, type, power.  We need only coordinates and type.


 There are three types of singular touch: ACTION_DOWN,  ACTION_MOVE and ACTION_UP. If we handle all touch events, we make 2 calls (ACTION_DOWN and ACTION_UP) instead 1. Because we must check, that type of touch is one of this. For example, ACTION_DOWN.



  Code:
@Override
    public boolean onTouchEvent(MotionEvent event){
        if(event.getAction()==event.ACTION_DOWN){//comparing type of action with constant 
     
           int x;//row of picked letter
           int y;//line of picked letter
     
           double red_height=(1-off_const)*height;//we have determined this variable before. It's part of height with letters
     
           x=(int) Math.floor( (event.getX()/((width/(double)rows))) );//Divide X to row width and floor this
           y=(int) Math.floor( ((event.getY()-off_const*height)/(red_height/(double)columns)) );//Analogically
     
     
           String letter;//Letter determining
     
           try{
               letter=alphabet.charAt(y*rows+x)+"";//Try get letter via row and line
           }
           catch(Exception e){
               letter="";//May be, user have clicked not in letter. We must return in this way
           }
     
           if (letter.length()==1){
               checkLetter(letter);//Checking
           }
        
        
        }
        return true; 
}
Next part

Download source of the game

Комментариев нет:

Отправить комментарий

Related Posts Plugin for WordPress, Blogger...