自己定义View 实现 五子棋
配图:
代码:
package com.example.fiveson;import java.util.LinkedList;import java.util.List;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;public class FiveSon extends View { public FiveSon(Context context) { super(context); // TODO Auto-generated constructor stub init(context, null); } public FiveSon(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(context, attrs); } public FiveSon(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // TODO Auto-generated constructor stub init(context, attrs); } private Paint paint = new Paint(); private Paint circlePaint = new Paint(); // 旗子: 信息 代表 第几行 第几列? private Listchesses = new LinkedList (); private void init(Context context, AttributeSet attrs) { chesses.add(new int[]{3,5}); chesses.add(new int[]{3,6}); } int spacing = 100; @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); int width = getWidth(); int height = getHeight(); //1 绘制 X 坐标 int num = width / spacing; paint.setColor(Color.BLACK); for(int i=0;i<=num;i++) { canvas.drawLine(spacing*i, 0, spacing*i, height, paint); } num = height/spacing; for(int i=0;i<=num;i++) { canvas.drawLine(0,spacing*i, width,spacing*i, paint); } //2 绘制Y 坐标 //3 绘制 旗子 if(!chesses.isEmpty()) { int count = chesses.size(); for(int i=0;i =(spacing/2)) { colcc++; } if(rowcc>=(spacing/2)) { rowcc++; } // 推断什么时候add int len = chesses.size(); if(len>0) { boolean has = false; for(int i = len-1;i>=0;i--) { int[] chs = chesses.get(i); if(rowNum == chs[0] && colNum == chs[1]) { has = true; break; } } if(!has) { chesses.add(new int[]{rowNum,colNum}); invalidate(); } }else { chesses.add(new int[]{rowNum,colNum}); invalidate(); } isComsumed = true; }else { isComsumed = super.onTouchEvent(event); } return super.onTouchEvent(event); } }