首先,对游戏进行分析,俄罗斯方块由七种方块及游戏界面组成,再进行细分,七种方块可拆分成四个最基本小方块,而游戏界面可分为窗体上嵌入一块游戏面板。所以,首先对游戏的最基本元素最基本小方块进行构造,编写一个Cell类
对Cell类进行分析,最基本小方块所具有的属性为行row,列col,图片Image;所具有的行为为左移,右移,下落(七种方块的左移、右移、下落实质上为最基本小方块的左移、右移、下落)。
注:在编写代码时,需要遵守JavaBean规范,即程序员在定义类时,默认遵守的一种规范。
代码如下:
package com.tetris;
import java.awt.image.BufferedImage;
public class Cell {
private int row;
private int col;
private BufferedImage image;
public Cell() {}
public Cell(int row, int col, BufferedImage image) {
super();
this.row = row;
this.col = col;
this.image = image;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
@Override
public String toString() {
return "Cell [row=" + row + ", col=" + col + ", image=" + image + "]";
}
//向左移动
public void left() {
col--;
}
//向右移动
public void right() {
col++;
}
public void drop() {
row++;
}
}
游戏最基本小方块类已经写完,接下来的第二步,就是需要用最基本小方块组合出来七种方块,而七种方块统一是由四个最基本小方块组成,所以我们可以先编写一个四格方块类,即取出四个最基本小方块放入二维数组中,构成一个四格方块,但是此时方块还未组成七种基本图形,只是在定义其行为及属性,为接下来的七种图形的构造提供方便。最终的七种方块的形状,由各个类继承本类来进行构造。对该类进行分析,四格方块所具有的属性为四个最基本小方块,方法同最基本小方块方法相同,即左移、右移、下落
代码如下:
package com.tetris;
public class Tetromino {
protected Cell[] cells=new Cell[4];
public void moveLefr() {
for(int i=0;i<cells.length;i++) {
cells[i].left();
}
}
public void moveRight() {
for(int i=0;i<cells.length;i++) {
cells[i].right();;
}
}
public void softDrop() {
for(int i=0;i<cells.length;i