1 package oo.day04; 2 //格子类 3 public class Cell { 4 5 int row; //行号 6 int col; //列号 7 8 Cell(int row,int col){ 9 this.row = row; 10 this.col = col; 11 } 12 Cell(int n){ 13 this(n,n); 14 } 15 Cell(){ 16 this(0,0); 17 } 18 19 void drop(){ //下落1格 20 row++; 21 } 22 void moveLeft(int n){ //左移n格 23 col-=n; 24 } 25 String getCellInfo(){ //获取格子行号和列号 26 return row+","+col; 27 } 28 29 void drop(int n){ //下落n格 30 row+=n; 31 } 32 void moveLeft(){ 33 col--; 34 } 35 36 }
1 package oo.day04; 2 //J型----子类 3 public class J extends Tetromino { 4 J(){ 5 this(0,0); 6 } 7 J(int row,int col){ 8 cells[0] = new Cell(row,col); 9 cells[1] = new Cell(row,col+1); 10 cells[2] = new Cell(row,col+2); 11 cells[3] = new Cell(row+1,col+2); 12 } 13 14 void print(){ //重写 15 System.out.println("I am a J"); 16 super.print(); 17 } 18 }
1 package oo.day04; 2 //T型----子类 3 public class T extends Tetromino { 4 T(){ 5 this(0,0); 6 } 7 T(int row,int col){ 8 super(); //默认的,调用父类的构造方法 9 this.cells[0] = new Cell(row,col); 10 this.cells[1] = new Cell(row,col+1); 11 this.cells[2] = new Cell(row,col+2); 12 this.cells[3] = new Cell(row+1,col+1); 13 } 14 15 void print(){ //重写 16 System.out.println("I am a T"); 17 super.print(); //调用父类的print方法 18 } 19 }
1 package oo.day04; 2 //四格拼板----父类 3 public class Tetromino { 4 Cell[] cells; //格子数组 5 Tetromino(){ 6 cells = new Cell[4]; 7 } 8 9 void drop(){ //下落 10 for(int i=0;i<cells.length;i++){ 11 cells[i].row++; 12 } 13 } 14 void moveLeft(){ //左移 15 for(int i=0;i<cells.length;i++){ 16 cells[i].col--; 17 } 18 } 19 void moveRight(){ //右移 20 for(int i=0;i<cells.length;i++){ 21 cells[i].col++; 22 } 23 } 24 void print(){ //输出格子坐标 25 for(int i=0;i<cells.length;i++){ 26 String str = cells[i].getCellInfo(); 27 System.out.println(str); 28 } 29 } 30 }
1 package oo.day04; 2 //T类、J类测试类 3 public class TJTest { 4 public static void main(String[] args) { 5 /* 6 Tetromino o1 = new T(2,5); //向上造型 7 printCell(o1); //先造型,再传值 8 9 J o2 = new J(2,5); 10 printCell(o2); //传值的同时造型 11 */ 12 13 T t = new T(2,5); 14 t.print(); 15 16 J j = new J(3,4); 17 j.print(); 18 19 } 20 21 //打墙+打T型 22 public static void printCell(Tetromino tt){ 23 for(int i=0;i<20;i++){ 24 for(int j=0;j<10;j++){ 25 26 boolean flag = true; //1.假设打- 27 for(int k=0;k<tt.cells.length;k++){ 28 if(tt.cells[k].row==i && tt.cells[k].col==j){ 29 flag = false; //2.打* 30 break; 31 } 32 } 33 if(flag){ //3.判断 34 System.out.print("- "); 35 }else{ 36 System.out.print("* "); 37 } 38 39 } 40 System.out.println(); 41 } 42 } 43 44 }