触摸屏幕后画布消失

时间:2019-06-11 12:07:56

标签: android android-canvas

我正在尝试创建一个用于玩Connect四的Android应用。 我的问题是,每当我触摸屏幕时,我的四个网格连接都消失了,相反,我应该放置的点仅出现在屏幕底部。我无法使用我的代码识别问题。画布只是钝地消失了,我应该丢下的圆点并没有移到应该去的地方。

主要活动:

    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new CFGrid(this));
        }
    }

连接四个班级:

    public class CFGrid extends View{

        private Paint paint = new Paint();
        private Paint red = new Paint();
        private Paint blue = new Paint();
        public CFGrid(Context context)
        {
            super(context);
            setWillNotDraw(false);
        }
        int w , h , cx = 0 , cy = 0 , i , j , c , p = 0;
        boolean game = false;
        int sx , sy;
        int[] count={6,6,6,6,6,6,6};
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float X = event.getX();
            float Y = event.getY();
            c = (int) Math.floor( 7 * X / w);
            c = Math.abs(c);
            if(event.getAction() == MotionEvent.ACTION_DOWN)
            {   if(X < = ( 40 + sx ) || Y < = ( 40 + sy ) )
                   {
                       game=true;
                       invalidate();
                   }

            }
            return true;
        }
        @Override
        protected void onDraw(Canvas canvas)
        {
            canvas.drawColor(Color.YELLOW);
            paint.setColor(Color.BLACK);
            w = Resources.getSystem().getDisplayMetrics().widthPixels;
            h = Resources.getSystem().getDisplayMetrics().heightPixels;
            sx = w / 14;
            sy = h / 16;
            for(i = sx ;  i < w && cx < 7 ; i = i + ( w/7 ) , cx++)
            {      cy = 0;
                for (j =  sy ; j < h && cy <6 ; j = j + ( h/8 ), cy++)
                {
                    canvas.drawCircle(i , j , 50 , paint);
                }
            }
            red.setColor(Color.RED);
            blue.setColor(Color.BLUE);
            if(game) {
                if (p == 0) {
                    canvas.drawCircle(sx + c * w / 7, sy + count[c] * h / 8, 50, red);
                    count[c] = count[c] - 1;
                    p = 1;
                } else if (p == 1) {
                    canvas.drawCircle(sx + c * w / 7, sy + count[c] * h / 8, 50 , blue);
                    count[c] = count[c] - 1;
                    p = 0;
                }
            }

        }

    }

0 个答案:

没有答案
相关问题