안 드 로 이 드 러시아 블록 (소스 코드)

전재 출처 표시:http://blog.csdn.net/waa_0618 / article / details / 54581457 소스 다운로드 주소http://download.csdn.net/download/waa_0618/9741351
생각:
  • 먼저 게임 배경 벽 을 그 려 야 한다.
  • 그 다음 에 사각형 과 사각형 단원 이 있어 야 한다.
  • 사각형 의 서로 다른 모양 으로 색깔 이 무 작위 로 생 긴 다.
  • 게임 의 제어 판.

  • 발생 할 수 있 는 문제 나 난점:
  • 경계 문제: ① 경계 에 있 을 때 사각형 은 더 이상 좌우 로 이동 할 수 없다.② 내 려 갈 때 경계 즉 바닥 에 도착 하면 계속 떨 어 질 수 없 으 며 이때 새로운 사각형 이 생 겨 야 한다.
  • 다른 사각형 과 접촉 하 는 문제: ① 떨 어 질 때 다른 사각형 에 부 딪 히 면 떨 어 지 는 것 을 멈춘다.② 좌우 로 이동 할 때 이동 하 는 과정 에서 다른 곳 에 빨리 닿 으 면 더 이상 좌우 로 이동 할 수 없다.
  • 사각형 의 제거: ① 사각형 의 제거 방법 을 사용 하 는 시간: 사각형 이 끝까지 떨 어 질 때 제거 해 야 할 줄 이 있 는 지 판단 한다.② 한 줄 을 제거 한 후 이 줄 위의 모든 사각형 을 한 줄 아래로 옮 겨 야 한다.
  • 사각형 의 회전: 현재 프로젝트 에서 저 는 시계 방향 으로 회전 합 니 다.① 회전 할 때 사각형 부분 이 경 계 를 넘 으 면 상대방 의 블록 을 평평 하 게 이동 시 켜 경계 이내 로 돌려 야 한다.(인터넷 에서 누군가가 회전 한 후에 경 계 를 초과 할 수 있 는 지 판단 하 는 것 을 본 적 이 있다. 만약 에 초과 할 수 있 으 면 회전 을 하지 않 는 다. 나 는 좋 지 않다 고 생각한다. 사각형 이 끝까지 떨 어 지지 않 으 면 모두 회전 할 수 있다 고 생각한다. 회전 할 공간 이 없 는 것 을 제외 하고)② 회전 할 공간 이 부족 하면 회전 할 수도 없다.공간 이 회전 으로 부족 하 다 는 뜻 은 가로 방향 은 두 개의 공간 만 있 고 사각형 이 회전 한 후에 세 개의 공간 을 차지 하 며 이때 도 회전 할 수 없다 는 것 이다.③ 더 이상 떨 어 질 수 없 거나 바닥 으로 떨 어 질 때 도 회전 할 수 없다
  • 제어 판: ① 게임 시작, 일시 정지, 계속, 끝, 이런 상 태 를 어떻게 통제 해 야 하 는 지, 그리고 게임 과 콘 솔 의 사건 과 관련 이 있다.
  • 발견 되 지 않 은 문제: 본인 의 능력 때문에 이렇게 만 할 수 있 습 니 다. 만약 에 문 제 를 발견 한 사람 이 있 으 면 댓 글로 교류 할 수 있 습 니 다. 문 제 를 고 르 는 것 을 환영 합 니 다.

  • 게임 의 운행 인 터 페 이 스 는 다음 과 같다. 기본 적 인 기능 과 조작 은 매우 간단 하 다.
    [외부 체인 이미지 저장 에 실 패 했 습 니 다. 원본 사이트 에 도 난 방지 체인 체제 가 있 을 수 있 습 니 다. 그림 을 저장 하여 직접 업로드 하 는 것 을 권장 합 니 다 (img - 3 ShqlKPe - 1595603247955) (https://img-blog.csdn.net/20170117150509362?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2FhXzA2MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)]
    다음은 프로젝트 코드 항목 파일 구조 직접 보기 Android 俄罗斯方块(附源码)_第1张图片
    다음은 각 유형의 기능 을 소개 한다.
  • TetrisViewAW. java 게임 의 메 인 인터페이스, 배경 벽 과 사각형 은 모두 TetrisViewAW. Java 에 있 습 니 다. 사용자 정의 View 입 니 다.코드 에 주석 을 많이 달 았 습 니 다. 모 르 는 것 은 메 시 지 를 남 길 수 있 습 니 다.또 한 가지 주의해 야 할 것 은 게임 을 멈 출 때 스 레 드 를 풀 고 좋 은 습관 을 기 르 는 것 이다
  • .
    /**
     *      Game   
     * 
     * @sign Created by wang.ao on 2017 1 12 
     */
    @SuppressLint("DrawAllocation")
    public class TetrisViewAW extends View {
    	/**        ,             */
    	public static final int beginPoint = 10;
    	/**            */
    	private static int max_x, max_y;
    	/**       */
    	private static int num_x = 0, num_y = 0;
    	/**       */
    	private static Paint paintWall = null;
    	/**             */
    	private static Paint paintBlock = null;
    	private static final int BOUND_WIDTH_OF_WALL = 2;
    	/**           */
    	private List blockUnits = new ArrayList();
    	/**           */
    	private List blockUnitBufs = new ArrayList();
    	/**           */
    	private List routeBlockUnitBufs = new ArrayList();
    	/**      allBlockUnits */
    	private List allBlockUnits = new ArrayList();
    	/**       Activity   */
    	private TetrisActivityAW father = null;
    	private int[] map = new int[100]; //                    
    	/**        */
    	private Thread mainThread = null;
    	//        
    	/**             */
    	private boolean gameStatus = false;
    	/**             */
    	private boolean runningStatus = false;
    	/**           */
    	private static final int color[] = { Color.parseColor("#FF6600"), Color.BLUE, Color.RED, Color.GREEN, Color.GRAY };
    	/**             , */
    	private int xx, yy;
    	/**   ,              */
    	private TetrisBlock tetrisBlock;
    	/**    */
    	private int score = 0;
    	/**         */
    	private int blockType = 0;
    
    	public TetrisViewAW(Context context) {
    		this(context, null);
    	}
    
    	public TetrisViewAW(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		if (paintWall == null) {//          
    			paintWall = new Paint();
    			paintWall.setColor(Color.LTGRAY);
    			paintWall.setStyle(Paint.Style.STROKE);
    			paintWall.setStrokeWidth(BOUND_WIDTH_OF_WALL + 1);
    		}
    		if (paintBlock == null) {//          
    			paintBlock = new Paint();
    			paintBlock.setColor(Color.parseColor("#FF6600"));
    		}
    		tetrisBlock = new TetrisBlock();
    		routeBlockUnitBufs = tetrisBlock.getUnits(beginPoint, beginPoint);
    		Arrays.fill(map, 0); //                        0
    		//     
    	}
    
    	/**
    	 *            activity
    	 * 
    	 * @param tetrisActivityAW
    	 */
    	public void setFather(TetrisActivityAW tetrisActivityAW) {
    		father = tetrisActivityAW;
    	}
    
    	@Override
    	protected void onDraw(Canvas canvas) {
    		super.onDraw(canvas);
    		max_x = getWidth();
    		max_y = getHeight();
    		RectF rel;
    		//     
    		num_x = 0;
    		num_y = 0;
    		for (int i = beginPoint; i < max_x - BlockUnit.UNIT_SIZE; i += BlockUnit.UNIT_SIZE) {
    			for (int j = beginPoint; j < max_y - BlockUnit.UNIT_SIZE; j += BlockUnit.UNIT_SIZE) {
    				rel = new RectF(i, j, i + BlockUnit.UNIT_SIZE, j + BlockUnit.UNIT_SIZE);
    				canvas.drawRoundRect(rel, 8, 8, paintWall);
    				num_y++;
    			}
    			num_x++;
    		}
    		//            
    		int len = blockUnits.size();
    		//     
    		// Toast.makeText(context, "" + len, Toast.LENGTH_SHORT).show();
    		for (int i = 0; i < len; i++) {
    			int x = blockUnits.get(i).x;
    			int y = blockUnits.get(i).y;
    			//          
    			paintBlock.setColor(color[blockUnits.get(i).color]);
    			rel = new RectF(x + BOUND_WIDTH_OF_WALL, y + BOUND_WIDTH_OF_WALL,
    					x + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL, y + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL);
    			canvas.drawRoundRect(rel, 8, 8, paintBlock);
    		}
    		//            
    		len = allBlockUnits.size();
    		//     
    		// Toast.makeText(context, "" + len, Toast.LENGTH_SHORT).show();
    		for (int i = 0; i < len; i++) {
    			int x = allBlockUnits.get(i).x;
    			int y = allBlockUnits.get(i).y;
    			paintBlock.setColor(color[allBlockUnits.get(i).color]);
    			rel = new RectF(x + BOUND_WIDTH_OF_WALL, y + BOUND_WIDTH_OF_WALL,
    					x + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL, y + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL);
    			canvas.drawRoundRect(rel, 8, 8, paintBlock);
    		}
    	}
    
    	/**
    	 *     
    	 */
    	public void startGame() {
    		gameStatus = true;
    		runningStatus = true;
    		if (mainThread == null || !mainThread.isAlive()) {
    			getNewBlock();
    			mainThread = new Thread(new MainThread());
    			mainThread.start();
    		}
    
    	}
    
    	/**
    	 *     
    	 */
    	public void pauseGame() {
    		runningStatus = false;
    	}
    
    	/**
    	 *     
    	 */
    	public void continueGame() {
    		runningStatus = true;
    	}
    
    	/**
    	 *     
    	 */
    	public void stopGame() {
    		//     ,       
    		runningStatus = false;
    		gameStatus = false;
    		mainThread.interrupt();
    		blockUnits.clear();
    		allBlockUnits.clear();
    		score = 0;
    		invalidate();
    	}
    
    	/**
    	 *     
    	 */
    	public void toLeft() {
    		if (BlockUnit.toLeft(blockUnits, max_x, allBlockUnits)) {
    			xx = xx - BlockUnit.UNIT_SIZE;
    		}
    		invalidate();
    	}
    
    	/**
    	 *     
    	 */
    	public void toRight() {
    		if (BlockUnit.toRight(blockUnits, max_x, allBlockUnits)) {
    			xx = xx + BlockUnit.UNIT_SIZE;
    		}
    		invalidate();
    	}
    
    	/**
    	 *       
    	 */
    	public void route() {
    		if (blockType == 3) {//                ,      
    			return;
    		}
    		if (routeBlockUnitBufs.size() != blockUnits.size()) {
    			routeBlockUnitBufs = tetrisBlock.getUnits(xx, yy);
    		}
    		for (int i = 0; i < blockUnits.size(); i++) {
    			routeBlockUnitBufs.get(i).x = blockUnits.get(i).x;
    			routeBlockUnitBufs.get(i).y = blockUnits.get(i).y;
    		}
    		for (BlockUnit blockUnit : routeBlockUnitBufs) {
    			int tx = blockUnit.x;
    			int ty = blockUnit.y;
    			blockUnit.x = -(ty - yy) + xx;
    			blockUnit.y = tx - xx + yy;
    		}
    		routeTran(routeBlockUnitBufs);
    		if (!BlockUnit.canRoute(routeBlockUnitBufs, allBlockUnits)) {
    			// Toast.makeText(father, "    ", Toast.LENGTH_SHORT).show();
    			return;
    		}
    		for (BlockUnit blockUnit : blockUnits) {
    			int tx = blockUnit.x;
    			int ty = blockUnit.y;
    			blockUnit.x = -(ty - yy) + xx;
    			blockUnit.y = tx - xx + yy;
    		}
    		routeTran(blockUnits);
    		invalidate();
    	}
    
    	/**
    	 *         ,     ,                ,   ,                ,
    	 *    ,       ,               
    	 */
    	public void routeTran(List blockUnitsBuf) {
    		boolean needLeftTran = false;
    		boolean needRightTran = false;
    		for (BlockUnit u : blockUnitsBuf) {
    			if (u.x < beginPoint) {
    				needLeftTran = true;
    			}
    			if (u.x > max_x - BlockUnit.UNIT_SIZE) {
    				needRightTran = true;
    			}
    		}
    		if (needLeftTran || needRightTran) {
    			for (BlockUnit u : blockUnitsBuf) {
    				if (needLeftTran) {
    					u.x = u.x + BlockUnit.UNIT_SIZE;
    				} else if (needRightTran) {
    					u.x = u.x - BlockUnit.UNIT_SIZE;
    				}
    			}
    			routeTran(blockUnitsBuf);
    		} else {
    			return;
    		}
    
    	}
    
    	/**
    	 *         
    	 */
    	private void getNewBlock() {
    		//        ,x    x    ,y       
    		this.xx = beginPoint + (num_x / 2) * BlockUnit.UNIT_SIZE;
    		this.yy = beginPoint;
    		if (blockUnitBufs.size() == 0) {
    			//            ,        
    			blockUnitBufs = tetrisBlock.getUnits(xx, yy);
    		}
    		blockUnits = blockUnitBufs;
    		blockType = tetrisBlock.blockType;
    		blockUnitBufs = tetrisBlock.getUnits(xx, yy);
    		if (father != null) {//             
    			father.setNextBlockView(blockUnitBufs, (num_x / 2) * BlockUnit.UNIT_SIZE);
    		}
    	}
    
    	/**
    	 *       
    	 * 
    	 * @sign Created by wang.ao on 2017 1 16 
    	 */
    	private class MainThread implements Runnable {
    
    		@Override
    		public void run() {
    			while (gameStatus) {
    				while (runningStatus) {
    					if (BlockUnit.canMoveToDown(blockUnits, max_y, allBlockUnits)) {
    						//           ,      ,   
    						BlockUnit.toDown(blockUnits, max_y, allBlockUnits);
    						yy = yy + BlockUnit.UNIT_SIZE;
    					} else {
    						/**
    						 *            ,         allBlockUnits ,
    						 *               ,           
    						 */
    						for (BlockUnit blockUnit : blockUnits) {
    							blockUnit.y = blockUnit.y + BlockUnit.UNIT_SIZE;
    							allBlockUnits.add(blockUnit);
    						}
    						for (BlockUnit u : blockUnits) {
    							//   map,                    
    							int index = (int) ((u.y - beginPoint) / 50); //       
    							map[index]++;
    						}
    						//       
    						int end = (int) ((max_y - 50 - beginPoint) / BlockUnit.UNIT_SIZE);
    						int full = (int) ((max_x - 50 - beginPoint) / BlockUnit.UNIT_SIZE) + 1;
    						try {
    							Thread.sleep(GameConfig.SPEED);
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    						for (int i = 0; i <= end; i++) {
    							/***
    							 *          (    ,          ,    )
    							 *     ,      ,           
    							 */
    							if (map[i] >= full) {
    								BlockUnit.remove(allBlockUnits, i);
    								score += 100;
    								map[i] = 0;
    								for (int j = i; j > 0; j--)
    									map[j] = map[j - 1];
    								map[0] = 0;
    								for (BlockUnit blockUnit : allBlockUnits) {
    									if (blockUnit.y < (i * BlockUnit.UNIT_SIZE + beginPoint)) {
    										blockUnit.y = blockUnit.y + BlockUnit.UNIT_SIZE;
    									}
    								}
    							}
    						}
    						father.runOnUiThread(new Runnable() {
    							@Override
    							public void run() {
    								/**
    								 *     
    								 */
    								father.score.setText("" + score);
    								invalidate();
    							}
    						});
    						try {
    							Thread.sleep(GameConfig.SPEED * 3);
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    						father.runOnUiThread(new Runnable() {
    							@Override
    							public void run() {
    								getNewBlock();
    								score += 10;
    								father.score.setText("" + score);
    							}
    						});
    					}
    					father.runOnUiThread(new Runnable() {
    						@Override
    						public void run() {
    							invalidate();
    						}
    					});
    					try {
    						Thread.sleep(GameConfig.SPEED);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    
    				}
    			}
    
    		}
    
    	}
    
    }
    
  • BlockUnit. 자바 사각형 의 유닛 블록 은 모두 러시아 사각형 을 해 본 적 이 있 고 모든 사각형 은 네 개의 유닛 블록 으로 구성 된다.유닛 이 빠 르 면 다음 과 같은 속성 이 있어 야 한다. ① 크기: 유닛 블록 의 크기 는 메 인 인터페이스의 용량 (유닛 블록 을 수용 하 는 수량) 을 결정 한다.② 색상: 각 유닛 블록 마다 하나의 색상 이 있 고 게임 인터페이스 (없 음) 를 미화 합 니 다.③ 좌표: X 축 좌표, Y 축 좌 표를 포함 하고 사각형 을 그 릴 때 유닛 블록 의 좌 표를 기점 으로 그립 니 다. 즉, 유닛 블록 의 좌 표 는 유닛 블록 이 인터페이스 에 있 는 왼쪽 상단 의 좌표 가 되 어야 합 니 다.
  • 이런 주요 기능 은 사각형 의 행방, 좌우 이동, 회전 가능 여 부 를 판단 하 는 등 기능 이 모두 이런 중에서 핵심 류 라 고 할 수 있다.
  • /**
     *          
     * 
     * @sign Created by wang.ao on 2017 1 13 
     */
    public class BlockUnit {
    	public static final int UNIT_SIZE = 50;
    	public static final int BEGIN = 10;
    	public int color;
    	//        
    	public int x, y;
    
    	public BlockUnit() {
    	}
    
    	public BlockUnit(int x, int y, int color) {
    		/*
    		 * @param             
    		 */
    		this.x = x;
    		this.y = y;
    		this.color = color;
    	}
    
    	/**
    	 *             ,1     ,2          
    	 * @param blockUnits          
    	 * @param max_x      X      ,  
    	 * @param allBlockUnits      
    	 * @return    true;    false
    	 */
    	public static boolean canMoveToLeft(List blockUnits, int max_x, List allBlockUnits) {
    		for (BlockUnit blockUnit : blockUnits) {
    			int x = blockUnit.x;
    			if (x - UNIT_SIZE < BEGIN) {
    				return false;
    			}
    			int y = blockUnit.y;
    			if (isSameUnit(x - UNIT_SIZE, y, allBlockUnits)) {
    				return false;
    			}
    		}
    		return true;
    	}
    
    	/**
    	 *             ,1     ,2          
    	 * @param blockUnits          
    	 * @param max_x      X      ,  
    	 * @param allBlockUnits      
    	 * @return    true;    false
    	 */
    	public static boolean canMoveToRight(List blockUnits, int max_x, List allBlockUnits) {
    		for (BlockUnit blockUnit : blockUnits) {
    			int x = blockUnit.x;
    			if (x + UNIT_SIZE > max_x - UNIT_SIZE) {
    				return false;
    			}
    			int y = blockUnit.y;
    			if (isSameUnit(x + UNIT_SIZE, y, allBlockUnits)) {
    				return false;
    			}
    		}
    		return true;
    	}
    	/**
    	 *             ,1     ,2          
    	 * @param blockUnits          
    	 * @param max_x      X      ,  
    	 * @param allBlockUnits      
    	 * @return    true;    false
    	 */
    	public static boolean canMoveToDown(List blockUnits, int max_y, List allBlockUnits) {
    		for (BlockUnit blockUnit : blockUnits) {
    			int x = blockUnit.x;
    			int y = blockUnit.y + UNIT_SIZE * 2;
    			if (y > max_y - UNIT_SIZE) {
    				return false;
    			}
    			if (isSameUnit(x, y, allBlockUnits)) {
    				return false;
    			}
    		}
    		return true;
    	}
    	public static boolean canRoute(List blockUnits, List allBlockUnits){
    		for (BlockUnit blockUnit: blockUnits) {
    			if(isSameUnit(blockUnit.x, blockUnit.y, allBlockUnits)){
    				return false;
    			}
    		}
    		return true;
    	}
    
    	/**
    	 *            
    	 * @param blockUnits
    	 * @param max_x
    	 * @param allBlockUnits
    	 * @return         , :true, :false
    	 */
    	public static boolean toLeft(List blockUnits, int max_x, List allBlockUnits) {
    		if (canMoveToLeft(blockUnits, max_x, allBlockUnits)) {
    			for (BlockUnit blockUnit : blockUnits) {
    				blockUnit.x = blockUnit.x - UNIT_SIZE;
    			}
    			return true;
    		}
    		return false;
    	}
    	/**
    	 *            
    	 * @param blockUnits
    	 * @param max_x
    	 * @param allBlockUnits
    	 * @return         , :true, :false
    	 */
    	public static boolean toRight(List blockUnits, int max_x, List allBlockUnits) {
    		if (canMoveToRight(blockUnits, max_x, allBlockUnits)) {
    			for (BlockUnit blockUnit : blockUnits) {
    				blockUnit.x = blockUnit.x + UNIT_SIZE;
    			}
    			return true;
    		}
    		return false;
    	}
    
    	/**
    	 *          
    	 * @param blockUnits
    	 * @param allBlockUnits
    	 * @return         , :true, :false
    	 */
    	public static void toDown(List blockUnits, int max_Y, List allBlockUnits) {
    		for (BlockUnit blockUnit : blockUnits) {
    			blockUnit.y = blockUnit.y + BlockUnit.UNIT_SIZE;
    		}
    	}
    
    	/**
    	 *                  
    	 * @param x
    	 * @param y
    	 * @param allBlockUnits
    	 * @return
    	 */
    	public static boolean isSameUnit(int x, int y, List allBlockUnits) {
    		for (BlockUnit blockUnit : allBlockUnits) {
    			if (Math.abs(x - blockUnit.x) < UNIT_SIZE && Math.abs(y - blockUnit.y) < UNIT_SIZE) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    	/**
    	 *     j       
    	 * @param allBlockUnits
    	 * @param j      
    	 */
    	public static void remove(List allBlockUnits, int j) {
    		for (int i = allBlockUnits.size() - 1; i >= 0; i--) {
    			/*
    			 * ①     ②  y         ,  j   units   
    			 */
    			if ((int) ((allBlockUnits.get(i).y - BEGIN) / 50) == j)
    				allBlockUnits.remove(i);
    		}
    	}
    }
    
  • Tetris Block. 자바 는 서로 다른 모양 의 사각형 을 만 드 는 데 사용 되 는데 모두 그 유형 이 있다.
  • /**
     *   
     * 
     * @sign Created by wang.ao on 2017 1 13 
     */
    public class TetrisBlock {
    	private static final int TYPE_SUM = 7;
    	public int blockType, blockDirection; //     ,    
    
    	private int color; //     
    
    	private int x, y; //     
    
    	public TetrisBlock() {
    
    	}
    
    	public TetrisBlock(int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    
    	public List getUnits(int x, int y) {
    		this.x = x;
    		this.y = y;
    		return returnUnit();
    	}
    
    	/**
    	 *         
    	 * @return
    	 */
    	public List returnUnit() {
    		List units = new ArrayList(); //       
    		blockType = (int) (Math.random() * TYPE_SUM) + 1; //         
    		blockDirection = 1; //       
    		color = (int) (Math.random() * 4) + 1; //         
    		units.clear();
    		switch (blockType) {
    		case 1://   
    			for (int i = 0; i < 4; i++) {
    				units.add(new BlockUnit(x + (-2 + i) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 2:
    			units.add(new BlockUnit(x + (-1 + 1) * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    			for (int i = 0; i < 3; i++) {
    				units.add(new BlockUnit(x + (-1 + i) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 3:
    			for (int i = 0; i < 2; i++) {
    				units.add(new BlockUnit(x + (i - 1) * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    				units.add(new BlockUnit(x + (i - 1) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 4:
    			units.add(new BlockUnit(x + (-1 + 0) * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    			for (int i = 0; i < 3; i++) {
    				units.add(new BlockUnit(x + (-1 + i) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 5:
    			units.add(new BlockUnit(x + (-1 + 2) * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    			for (int i = 0; i < 3; i++) {
    				units.add(new BlockUnit(x + (-1 + i) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 6:
    			for (int i = 0; i < 2; i++) {
    				units.add(new BlockUnit(x + (-1 + i) * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    				units.add(new BlockUnit(x + i * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		case 7:
    			for (int i = 0; i < 2; i++) {
    				units.add(new BlockUnit(x + i * BlockUnit.UNIT_SIZE, y - BlockUnit.UNIT_SIZE, color));
    				units.add(new BlockUnit(x + (-1 + i) * BlockUnit.UNIT_SIZE, y, color));
    			}
    			break;
    		}
    		return units;
    	}
    
    
  • NextBlockView. 자바 는 게임 메 인 인터페이스의 축소판 으로 다음 에 나타 날 사각형 을 표시 하 는 데 사 용 됩 니 다. 유 저 는 다음 사각형 의 모양 과 색 을 명확 하 게 알 수 있 습 니 다.
  • /**
     *          
     * 
     * @sign Created by wang.ao on 2017 1 13 
     */
    @SuppressLint("DrawAllocation")
    public class NextBlockView extends View {
    	/**        ,             */
    	public static final int beginPoint = 10;
    	/**            */
    	private static int max_x, max_y;
    	private List blockUnits = new ArrayList();
    	/**       */
    	private static Paint paintWall = null;
    	private static final int BOUND_WIDTH_OF_WALL = 2;
    	private static Paint paintBlock = null;
    	private int div_x = 0;
    	//          
    	private static final int color[] ={ Color.parseColor("#FF6600"), Color.BLUE, Color.RED, Color.GREEN, Color.GRAY };
    
    	public NextBlockView(Context context) {
    		this(context, null);
    	}
    
    	public NextBlockView(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		if (paintWall == null) {//          
    			paintWall = new Paint();
    			paintWall.setColor(Color.LTGRAY);
    			paintWall.setStyle(Paint.Style.STROKE);
    			paintWall.setStrokeWidth(BOUND_WIDTH_OF_WALL + 1);
    		}
    		if (paintBlock == null) {//          
    			paintBlock = new Paint();
    			paintBlock.setColor(Color.parseColor("#FF6600"));
    		}
    	}
    
    	public void setBlockUnits(List blockUnits, int div_x) {
    		this.blockUnits = blockUnits;
    		this.div_x = div_x;
    		invalidate();
    	}
    
    	@Override
    	protected void onDraw(Canvas canvas) {
    		super.onDraw(canvas);
    		max_x = getWidth();
    		max_y = getHeight();
    		RectF rel;
    		//     
    		int len = blockUnits.size();
    		//     
    		// Toast.makeText(context, "" + len, Toast.LENGTH_SHORT).show();
    		for (int i = 0; i < len; i++) {
    			paintBlock.setColor(color[blockUnits.get(i).color]);
    			int x = blockUnits.get(i).x - div_x + BlockUnit.UNIT_SIZE * 2;
    			int y = blockUnits.get(i).y + BlockUnit.UNIT_SIZE * 2;
    			rel = new RectF(x + BOUND_WIDTH_OF_WALL, y + BOUND_WIDTH_OF_WALL,
    					x + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL, y + BlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL);
    			canvas.drawRoundRect(rel, 8, 8, paintBlock);
    			rel = new RectF(x, y, x + BlockUnit.UNIT_SIZE, y + BlockUnit.UNIT_SIZE);
    			canvas.drawRoundRect(rel, 8, 8, paintWall);
    		}
    	}
    
    }
    
  • GameConfig. java 는 사각형 의 낙하 속 도 를 설정 하 는 데 사 용 됩 니 다
  • public class GameConfig {
    	/**       */
    	public static final int SPEED = 300;
    }
    
  • Tetris Activity AW. 자바 메 인 화면 은 게임 메 인 화면 과 콘 솔 을 포함 하여 간단 하고 코드 를 직접 붙 입 니 다.
  • public class TetrisActivityAW extends Activity {
    	private NextBlockView nextBlockView;
    	private TetrisViewAW tetrisViewAW;
    	private TextView gameStatusTip;
    	public TextView score;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_tetris_activity_aw);
    		nextBlockView = (NextBlockView) findViewById(R.id.nextBlockView1);
    		tetrisViewAW = (TetrisViewAW) findViewById(R.id.tetrisViewAW1);
    		tetrisViewAW.setFather(this);
    		gameStatusTip = (TextView) findViewById(R.id.game_staus_tip);
    		score = (TextView) findViewById(R.id.score);
    	}
    
    	public void setNextBlockView(List blockUnits, int div_x) {
    		nextBlockView.setBlockUnits(blockUnits, div_x);
    	}
    
    	/**
    	 *     
    	 * 
    	 * @param view
    	 */
    	public void startGame(View view) {
    		tetrisViewAW.startGame();
    		gameStatusTip.setText("     ");
    	}
    
    	/**
    	 *     
    	 */
    	public void pauseGame(View view) {
    		tetrisViewAW.pauseGame();
    		gameStatusTip.setText("     ");
    	}
    
    	/**
    	 *     
    	 */
    	public void continueGame(View view) {
    		tetrisViewAW.continueGame();
    		gameStatusTip.setText("     ");
    	}
    
    	/**
    	 *     
    	 */
    	public void stopGame(View view) {
    		tetrisViewAW.stopGame();
    		score.setText(""+0);
    		gameStatusTip.setText("     ");
    	}
    
    	/**
    	 *     
    	 */
    	public void toLeft(View view) {
    		tetrisViewAW.toLeft();
    	}
    
    	/**
    	 *     
    	 */
    	public void toRight(View view) {
    		tetrisViewAW.toRight();
    	}
    	/**
    	 *     
    	 */
    	public void toRoute(View view) {
    		tetrisViewAW.route();
    	}
    }
    
  • TetrisActivity AW activity 의 xml 파일

  • 전체 항목 이 바로 이것들 이 고 코드 는 이미 전부 붙 여 졌 다.전체 항목 을 쓸 때 는 매우 간단 하 다 고 생각 했 지만 많은 문제 에 부 딪 혔 지만 이미 해결 되 었 다.bug 를 찾 아 오신 것 을 환영 합 니 다. 모두 함께 발전 합 니 다.
    원본 다운로드 주소
    http://download.csdn.net/download/waa_0618/9741351

    좋은 웹페이지 즐겨찾기