まず、ブロックの残りの数をカウントするblkreという変数を用意します。この変数は、ブロックの表示処理の時の毎回ブロックの数をカウントします。
そして、プログラムの一番最後で、blkreが0になった時の処理を加えます。ただし、draw()を中断して、メッセージを表示するのは、ミスをした場合、ブロックが無くなった場合の2通りが考えられます。そこで、modeとい変数を用意して、mousePressed()のなかで継続なのか、終了なのかの判断をします。
ソースリスト
ブロック崩し完成版!
//ウインドウの大きさ
int yoko=400,tate=600;
//ボールの半径を5
int r=5;
//ボールの最初の位置
float x0=200,y0=350;
//ボールの座標
float x=x0,y=y0;
//移動方向の初期値
float dx=2,dy=2;
//ラケットの半分の長さ
float rtw=25;
float rtx,rty=550;
//ブロックの段数
int blkno=10;
//ブロック(block)の幅
int blkw=40;
//上下の間隔
int blksp=30;
//残りのブロック数
int blkre;
//ブロックの配置用配列
int[][] blk={
{1,0,1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1,0,1},
{1,1,0,0,1,1,0,0,1,1},
{0,0,1,1,0,0,1,1,0,0},
{1,0,1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1,0,1},
{1,1,0,0,1,1,0,0,1,1},
{0,0,1,1,0,0,1,1,0,0},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1}};
//メッセージのフォントの大きさ
int msgp=24;
//中断時のモード指定
//1ならば継続、0ならば終了
int mode;
void setup()
{
size(yoko,tate);
//カラーモードの設定
//RGBの各色を256まで使えるようにする
colorMode(RGB,255);
//背景色を黒にする
smooth();
frameRate(120);
}
void draw()
{
int i,j,byd,byy;
background(0,0,0);
fill(248,252,13);/*黄色で塗りつぶす*/
stroke(248,252,13);/*線も黄色で*/
ellipse(x,y,2*r,2*r);/*ボールを描く*/
fill(255,255,255);
rtx = mouseX;
//ラケットを描く
stroke(255,255,255);/*線を白く*/
line(rtx - rtw,rty,rtx + rtw,rty);/*ラケットを描く*/
//ブロックを描く
blkre=0;
stroke(255,255,255);/*線を白く*/
for(i=0;i<blkno;i++){
for(j=0;j<blkno;j++){
if( blk[i][j] != 0 ){
line(j*blkw,(i+1)*blksp,(j+1)*blkw,(i+1)*blksp);
blkre++;
}
}
}
//壁あたり判定
if( x+dx+r > yoko)//右の壁の判断
dx = -dx;
if( x+dx-r < 0)//左の壁の判断
dx = -dx;
/* if( y+dy+r > tate)//下の壁の判断
dy=-dy;
*/
if( y+dy-r < 0)//上の壁の判断
dy=-dy;
//ラケットの上面あたり判定
if( y+r >= rty && y+r <= rty+dy && x>=rtx - rtw && x<=rtx+ rtw){
dy = -dy;
}
//ブロックのあたり判定
byd=int(y / blksp);
byy=int(y % blksp);
if( byd >= 1 && byd <= blkno && byy <= r){/*上のブロックにぶつかる*/
if(blk[byd-1][int(x/blkw)] != 0){
dy = -dy;
blk[byd-1][int(x/blkw)]=0;
}
}
if( byd < blkno && byy >= blksp-r){/*下のブロックにぶつかる*/
if(blk[byd][int(x/blkw)] != 0){
dy = -dy;
blk[byd][int(x/blkw)]=0;
}
}
x +=dx;
y +=dy;
//ミス処理
if( y >= tate ){
mode=1;
x=x0;
y=y0;
fill(256,100,100);
textSize(msgp);
textAlign(CENTER);
text("Miss Miss!",yoko/2,tate/2);
text("Press Mouse Left-Button",yoko/2,tate/2+msgp);
noLoop();
}
//クリア処理
if( blkre==0){
mode=0;
fill(62,240,53);
textSize(msgp*2);
textAlign(CENTER);
text("Clear Clear!",yoko/2,tate/2);
textSize(msgp);
text("Press Mouse Left-Button",yoko/2,tate/2+msgp*2);
noLoop();
}
}
void mousePressed()
{
if(mouseButton == LEFT) {
//マウスの左ボタンを押したときの処理
if(mode==1)/*1ならば継続,1以外なら終了*/
loop();
else exit();
}
}
結構、長いプログラムになりました。どうでしょうか?
疑問
もう少し、アレンジすることはできますか?
答え
それは、プログラムしだいです。
ポイント
例えば、
いろいろと、工夫をして楽しんでください。おまけのページがあります。