ClearableTrash.java
/** 消去のルールを組み込んだClearableTrashクラス */
public class ClearableTrash extends Trash implements Clearable{
/** 作業用の表 */
protected boolean toBeClear[][];
/** コンストラクタ */
ClearableTrash( int iMax, int jMax ) {
super( iMax, jMax ); // Trashクラスのコンストラクタ
toBeClear = new boolean[iMax][jMax];
initTable( toBeClear );
}
/** 消去を実行するメソッド(再起的に作業はしない)
* クリアすべきセルが見つからないとfalseを返す */
public boolean clearCells(){
if( !checkClear() ) return false;
copyStates( state, old_state );
for( int i=0; i<iMax; i++ )
for( int j=0; j<jMax; j++ )
if( toBeClear[i][j] ) {
state[i][j] = EMPTY;
toBeClear[i][j] = false;
}
moveCells();
checkRepaint();
return true;
}
/** 消去すべきセルのリストアップを行うメソッド
* 縦・横・斜めに3個以上の同じ色が並ぶと消去
* 返値はクリアするセルが存在するかどうか */
public boolean checkClear(){
boolean flag = false;
int i, j;
// テーブル初期化
initTable( toBeClear );
// 横に3つ以上同じ色のセルが並んだ場所をチェックする
for( j=0; j<jMax; j++ )
for( i=0; i<iMax-2; i++ ) {
if( state[i][j] == EMPTY ) continue;
if( state[i+1][j] != state[i][j] ) continue;
if( state[i+2][j] != state[i][j] ) continue;
toBeClear[i][j]=true;
toBeClear[i+1][j]=true;
toBeClear[i+2][j]=true;
flag=true;
}
// 縦に3つ以上同じ色のセルが並んだ場所をチェックする
for( i=0; i<iMax; i++ )
for( j=0; j<jMax-2; j++ ) {
if( state[i][j] == EMPTY ) continue;
if( state[i][j+1] != state[i][j] ) continue;
if( state[i][j+2] != state[i][j] ) continue;
toBeClear[i][j]=true;
toBeClear[i][j+1]=true;
toBeClear[i][j+2]=true;
flag=true;
}
// ななめに3つ以上同じ色のセルが並んだ場所をチェックする
for( i=0; i<iMax-2; i++ )
for( j=0; j<jMax-2; j++ ) {
if( state[i][j] == EMPTY ) continue;
if( state[i+1][j+1] != state[i][j] ) continue;
if( state[i+2][j+2] != state[i][j] ) continue;
toBeClear[i][j]=true;
toBeClear[i+1][j+1]=true;
toBeClear[i+2][j+2]=true;
flag=true;
}
for( j=0 ; j<jMax-2 ; j++ )
for( i=2 ; i<iMax ; i++ ) {
if( state[i][j] == EMPTY ) continue;
if( state[i-1][j+1] != state[i][j] ) continue;
if( state[i-2][j+2] != state[i][j] ) continue;
toBeClear[i][j]=true;
toBeClear[i-1][j+1]=true;
toBeClear[i-2][j+2]=true;
flag=true;
}
return flag;
}
/** 消去に伴うセルの移動を行うメソッド */
public void moveCells(){
for( int i=0; i<iMax; i++ )
for( int j=jMax-1; j>0; j-- )
if( state[i][j] == EMPTY ) {
boolean flag = false;
for( int k=j; k>0; k-- ) {
state[i][k]=state[i][k-1];
if( state[i][k]!=EMPTY ) flag = true;
}
state[i][0] = EMPTY;
if( flag ) j++; else continue;
}
}
}