在”java俄罗斯方块小游戏编写心得02”中,我们已经做到了方块的各种功能的实现,那么接下来我们需要一个destroyLine()方法来对方块进行消除。我们需要想一个问题,当一个方块下落后,最多消除的行数也就只是方块可以达到的最大的行数。所以我们首先需要从方块行数最低的那个开始向下扫描,扫描每一个最基本小方块所处的行是否已经满了,如果没满,那么继续向下扫描,如果满了,那么该行消除,该行的上一行下落到该行,一定不可以从下向上扫描,如果从下向上扫描,可能会导致漏消。注:该方法应该在softMoveDropAction()、hardMoveDropAction()方法中均进行调用,否则会导致仅仅自由下落后才能消除,手动进行操作后无法进行消除。注: wall[n]=new Cell[10];wall[n]=wall[n-1];这个方法是不可取的
代码如下:
package com.CSDN;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tetris extends JPanel{
public void start() {
while(true) {
try {
Thread.sleep(300);
}catch(InterruptedException e) {
e.printStackTrace();;
}
if(canDrop()) {
currentOne.moveDrop();
}else {
landToWall();
destroyLine();
currentOne=nextOne;
nextOne=Tetromino.RandomeOne();
}
repaint();
}
}
public void softMoveDropAction() {
if(canDrop()) {
currentOne.moveDrop();
}else {
landToWall();
destroyLine();
currentOne=nextOne;
nextOne=Tetromino.RandomeOne();
}
}
public void hardMoveDropAction() {
while(canDrop()) {
currentOne.moveDrop();
}
landToWall();
destroyLine();
currentOne=nextOne;
nextOne=Tetromino.RandomeOne();
}
public void destroyLine() {
Cell[] cells=currentOne.cells;
int row=cells[0].getRow();
for(int i=0;i<4;i