思考:俄罗斯方块游戏的最小单元------单个方块
游戏界面呈现---------四个各种形式的方块-------------抽象出长度为4的方块数组
所以先建立方块类
第一步:建立方块类型,并添加移动方法
/**
* 经典俄罗斯方块游戏:
画面最多能放入20行,10列的方块
画面中的最小单元:
是一个小方块
设计需求分析:最多有200个方块,这些方块有共同特征
有共同行为
最小单元:Cell来定义方块这种事物
成员变量:行号 row,列号col
方法(行为):drop()
left()
right()
重载上述方法,通过形参决定移动的步数
toString();*/
public class Cell {
int row;
int col;
public Cell(int row,int col){
this.row = row;
this.col = col;
}
//每次下落一行
public void drop(){
row++;
}
//每次向左移动一列
public void left(){
col--;
}
//每次向右移动一列
public void right(){
col++;
}
//每次下落n行
public void drop(int n){
row+=n;
}
//向左移动:每次移动n列
public void left(int n){
col-=n;
}
//向右移动:每次移动n列
public void right(int n){
col+=n;
}
/**打印墙与当前对象
* 墙:20行10列的减号
* 当前对象:*
* */
public void printWall(){
for(int i = 0;i<20;i++){
for(int j = 0;j<10;j++){
if(i==row&&j==col){
System.out.print("*");
}else{
System.out.print("-");
}
}
System.out.println();
}
}
//返回对象的详细信息
public String toString(){
return "("+row+","+col+")";
}
}
第二部:编写父类Tetomino
/**
* 俄罗斯方块类型
* 共同特征:方块数组
* 共同行为:向左、向右、向下移动等
* */
public class Tetromino {
Cell[] cs ;
public Tetromino(){
cs = new Cell[4];
}
public void moveLeft(){
for(int i = 0 ;i<cs.length;i++){
cs[i].left();
}
}
public void moveRight(){
for(int i = 0;i<cs.length;i++){
cs[i].right();
}
}
public void moveDrop(){
for(int i = 0;i<cs.length;i++){
cs[i].drop();
}
}
public String toString(){
String line = "";
for(int i = 0;i<cs.length;i++){
line+=cs[i];
}
return line;
}
public void printWall(){
for(int i = 0;i<20;i++){
for(int j = 0;j<10;j++){
boolean f = true;
for(int h = 0;h<cs.length;h++){
if(cs[h].row==i&&cs[h].col==j){
f = false;
break;
}
}
if(f){
System.out.print("-");
}else{
System.out.print("*");
}
}
System.out.println();
}
}
}
第三部:编写不同形状方块组合的类
/**
* I是Tetromino的子类,可以继承父类中的成员变量cs,也继承了父类中的向左,
* 向右,向下移动的方法
* */
public class I extends Tetromino{
public I(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,3);
cs[2] = new Cell(0,5);
cs[3] = new Cell(0,6);
}
}
public class J extends Tetromino{
public J(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,3);
cs[2] = new Cell(0,5);
cs[3] = new Cell(1,5);
}
}
public class L extends Tetromino{
public L(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,3);
cs[2] = new Cell(0,5);
cs[3] = new Cell(1,3);
}
}
public class O extends Tetromino {
public O(){
cs[0] = new Cell(0,3);
cs[1] = new Cell(0,4);
cs[2] = new Cell(1,3);
cs[3] = new Cell(1,4);
}
}
public class S extends Tetromino {
public S(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,5);
cs[2] = new Cell(1,3);
cs[3] = new Cell(1,4);
}
}
public class T extends Tetromino{
public T(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,3);
cs[2] = new Cell(0,5);
cs[3] = new Cell(1,4);
}
}
public class Z extends Tetromino {
public Z(){
cs[0] = new Cell(0,4);
cs[1] = new Cell(0,3);
cs[2] = new Cell(1,4);
cs[3] = new Cell(1,5);
}
}