前言:
写俄罗斯方块需要一些材料,以下为百度云链接,点击下载(若链接失效,请联系我)
正文:
第一步:
分析游戏界面(以下界面并不完成,只是一部分),通过游戏界面,抽象出几种类型
从图中我们可以看出有一个表格(就是界限,我们称之为墙,在此例子中墙的大小为20行10列)和元胞(就是一个方格)。
俄罗斯方块下落的图案有七种类型,还会显示下一个图案的类型。这七种类型类似于字母T、I、O、J、L、S、Z,一种类型对应一种颜色。(意思就是T类型的就用黄色的四个元胞表示,O类型用红色的四个元胞表示,以下图片在资源包中含有)
然后每个类型都可以向左移动,向右移动和向下移动。
第二步:
定义类型
- 元胞用Cell类表示,表示一个方格
共同特征:行号、列号,图片
共同行为:向左、向右、向下移动、提供JavaBean相关的规范
//Cell.java
package com.tetris;
/**
* 俄罗斯方块中的最小单位:一个方格
* 特征:
* row---行号
* col---列号
* image---对应的图片
* 行为:
* 向左移动---left()
* 向右移动---right()
* 下落---drop()
* @author DELL
*
*/
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() {
// TODO Auto-generated method stub
return "[row="+row+",col="+col+"]";
}
public void left() {
col--;
}
public void right() {
col++;
}
public void drop() {
row++;
}
}
因为每种类型都是由四个元胞组成的,每种类型都可以向左、向右、向下移动,所以我们可以提取一个父类,我们取名为Tetromino
2 . Tetromino类,是所有七种类型的父类
共同特征:cells-->四个元胞(用数组表示)-->权限修饰词protected(方便之后七种类型继承时可以 获取)
共同行为:向左、向右、向下移动、提供JavaBean相关的规范
额外的方法:在俄罗斯方块中,我们会随机获得一种类型的图案,为此,我们需要写一个方法来随机获得一个类型。
//Tetromino.java
package com.tetris;
import java.util.Arrays;
/**
* 四格方块
* 属性:
* cells---四个方块
* 行为:
* moveLeft()---左移动
* moveRight()---右移动
* softDrop()---软下落
* @author DELL
*
*/
public class Tetromino {
protected Cell[] cells=new Cell[4];
public Cell[] getCells() {
return cells;
}
public void setCells(Cell[] cells) {
this.cells = cells;
}
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();
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "["+Arrays.toString(cells)+"]";
}
/*
* 随机生成一个四格方块
*/
public static Tetromino randomOne() {
Tetromino t=null;
int n=(int)(Math.random()*7);
switch(n) {
case 0:t=new T();break;//获取T类型,以下依次类推
case 1:t=new I();break;
case 2:t=new O();break;
case 3:t=new S();break;
case 4:t=