前回のコードを改良して、ゲームを改良してみましょう。
これまでは(当然ですが)ボールは一つだけでした。これを、1度に10個のボールが一斉に動くように修正します。
敵のラケットは、これまでボールを追いかけていましたが、複数のボールを追いかけるのはちょっと難しいので、ラケットを大きくして上下に動くだけにしてみました。
ボールの動きは Ball クラスの中に記述しました。セットはなくし、100点とったら勝ちとしました。クラスの簡単な説明は前回の投稿をご覧ください。
float racketY = 0;
float enemyY = 1;
int enemyDir = 1;
float easing;
int myScore = 0;
int enemyScore = 0;
Ball[] balls = new Ball[10];
class Ball{
float x, y, xSpeed, ySpeed, r, xDir, yDir;
Ball(){
x = width/2;
y = height/2;
xSpeed = random(5);
ySpeed = random(5);
r = random(4, 10);
xDir = 1;
yDir = 1;
}
void move(){
fill(255);
ellipse(x, y, r, r);
if ((y>height) || (y<0))
yDir *= -1;
if ((x >= 440) && (x <= 448) && (y > racketY-25) && (y < racketY+30))
xDir *= -1;
if ((x <= 48) && (x >= 40) && (y > enemyY) && (y < enemyY+160))
xDir *= -1;
if (x > width) {
enemyScore ++;
x = width/2;
y = height/2;
xSpeed = random(1, 4);
ySpeed = random(1, 4);
}
else if(x < 0) {
myScore ++;
x = width/2;
y = height/2;
xSpeed = random(1, 4);
ySpeed = random(1, 4);
}
x += xSpeed * xDir;
y += ySpeed * yDir;
xSpeed += 0.01;
ySpeed += 0.01;
}
}
void setup() {
size (480,320);
racketY = height/2;
easing = 0.1;
for (int i = 0; i < balls.length; i++){
balls[i] = new Ball();
}
}
void draw() {
background(0);
for(int i = 0; i < 10; i++) balls[i].move();
strokeWeight (1);
stroke(255);
for ( int i = 0; i < height; i += 10 ){
line(width/2, i, width/2, i+5);
}
//my racket
float targetY = mouseY;
racketY += (targetY - racketY) * easing;
rect(440, racketY-25, 8, 50);
//enemy racket
rect(40, enemyY, 8, 160);
enemyY += enemyDir;
if((enemyY < 0) || ((enemyY+160) > width)) enemyDir *= -1;
// score display
textAlign(CENTER, CENTER);
textSize(30);
text(enemyScore, 120, 20);
text(myScore, 360, 20);
// end message
textSize(80);
if (enemyScore >= 100){
text("You LOSE!", width/2, 130);
textSize(40);
text("Click to restart", width/2, 200);
}
else if (myScore >= 100){
text("You WIN!", width/2, height/2-30);
textSize(40);
text("Click to restart", width/2, height/2+30);
}
if(mousePressed){
for (int i = 0; i < 10; i++){
balls[i].x = width/2;
balls[i].y = height/2;
}
myScore = 0;
enemyScore = 0;
}
}


難しいです。勝てません。敵のラケットの大きさを調整するなどしてレベル調整してください。案外おもしろいです。