Java ——简易俄罗斯方块

一、将对象抽象为类
首先考虑俄罗斯方块游戏中含有哪些具体的对象 , 对象中含有哪些具体属性和方法 , 然后用代码来实现 。
建立如下类:
Cell类:代表最小的方格单位 , 构成7种图形的最基本图形 。
含有row(行号) , col(列号) , image(对应的图片)属性 , 
含有left(左移) , right(右移) , drop(下落)方法 。
类:代表由4个最小方格构成的7种图形的合集 。
含有cells(四个方块)属性 , 
含有(四格方块向左移动) , (四格方块向右移动) , (软下落) , (随机生成一个四格方格)方法 。
T类继承于类:

Java ——简易俄罗斯方块

文章插图
I类继承于类:
L类继承于类:
Java ——简易俄罗斯方块

文章插图
S类继承于类:
Z类继承于类:
O类继承于类:
J类继承于类:
Java ——简易俄罗斯方块

文章插图
类:俄罗斯方块的主方法类 , 包括了游戏运行过程中所需要的众多方法 。
含有(正在下落的四格方块) , (即将下落的四格方块) , Cell[][]wall(二维数组的表格 , 代表墙)属性 。
二、类的实现
Notes:各类实现过程中要符合规范 。
Cell类:
package com.tetris;import java.awt.image.BufferedImage;/** 俄罗斯方块中的最小单位:方格* 特征(属性):* row--行号* col--列号* image--对应的图片* * 行为(方法)*left();*right();*drop();*/public class Cell {private int row; //行private int col; //列private BufferedImage image;public Cell(int row, int col, BufferedImage image) {super();this.row = row;this.col = col;this.image = image;}public Cell() {super();// TODO Auto-generated constructor stub}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;}@Overridepublic String toString() {return "(" + row + ", " + col + ")";}//向左移动public void left(){col--;}//向右移动public void right(){col++;}//向下移动public void drop(){row++;}}
类:

package com.tetris;import java.util.Arrays;import javax.xml.transform.Templates;/** 四格方块* 属性:* ---cells , ----四个方块* * 行为:*moveLeft()*moveRight()*softDrop()*/public class Tetromino {protected Cell[] cells=new Cell[4];//四格方块向左移动//实际上:就是每个方块向左移动public void moveLeft(){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++) {cells[i].drop();}}@Overridepublic String toString() {return "[" + Arrays.toString(cells) + "]";}//随机生成一个四格方块public static Tetromino randomOne(){Tetromino t = null;int num=(int)(Math.random()*7);switch (num){case 0:t=new T();break;case 1:t=new O();break;case 2:t=new I();break;case 3:t=new J();break;case 4:t=new L();break;case 5:t=new S();break;case 6:t=new Z();break;default:break;}return t;}}
T类继承于类:
【Java ——简易俄罗斯方块】