Pongを作る(6) 終了条件を加える

現状では点数が無限に増え、ゲームが終わりません。終了条件を加えましょう。

3セット取ればメッセージが表示され終了としましょう。

textSize(80);
if (enemySet >= 3){
  text("You LOSE!", width/2, 130);
  textSize(40);
  text("Click to restart", width/2, 200);
}
else if (mySet >= 3){
  text("You WIN!", width/2, height/2-30);
  textSize(40);
  text("Click to restart", width/2, height/2+30);
}

メッセージの縦位置は適当です。
さて、”Click to restart” と記述しました。ついでに、リセット機能も追加しましょう。
リセットのためには、スコアとセットを 0 にし、ボールの位置を中央に戻せばOKです。ボールの X 方向、Y 方向のスピードも 1 に設定しておきます。

if(mousePressed){
  ballX = width/2;
  ballY = height/2;
  mySet = 0;
  myScore = 0;
  enemySet = 0;
  enemyScore = 0;
  xSpeed = 1;
  ySpeed = 1;
}

これで、ゲームが終了するようになりました(確認のため、3点で1セットとるようにしています)。

上記の状態でクリックすると、点数とセット、ボール位置がリセットされます。

ここまでのコードです。

float ballX, ballY;
float racketY;
int xDir, yDir;
float xSpeed, ySpeed;
float enemyY;
float easing;
int myScore = 0;
int enemyScore = 0;
int mySet = 0;
int enemySet = 0;

void setup() {
  size (480,320);
  ballX = width/2;
  ballY = height/2;
  racketY = height/2;
  easing = 0.1;
  xDir = 1;
  yDir = 1;
  xSpeed = 1;
  ySpeed = 1;
}

void draw() {
  background(0);
  
  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 
  enemyY += (ballY - enemyY) * easing; 
  rect(40, enemyY-25, 8, 50);
 
  ellipse(ballX, ballY, 6, 6); 
  if((ballY+3>height) || (ballY-3<0)) 
    yDir *= -1; 
  if ((ballX+3 >= 440) && (ballX+3 <= 448) && (ballY > racketY-25) && (ballY < racketY+30))
    xDir *= -1;
  if ((ballX-3 <= 48) && (ballX-3 >= 40) && (ballY > enemyY-25) && (ballY < enemyY+25)) 
    xDir *= -1; 
  if (ballX+3 > width) {
    enemyScore ++;
    ballX = width/2;
    ballY = height/2;
    xSpeed = random(1, 4);
    ySpeed = random(1, 4);
  }
  else if(ballX-3 < 0) { 
    myScore ++; 
    ballX = width/2; 
    ballY = height/2; 
    xSpeed = random(1, 4); 
    ySpeed = random(1, 4); 
  } 

  ballX += xSpeed * xDir; 
  ballY += ySpeed * yDir; 
  
  textAlign(CENTER, CENTER); 
  textSize(30); 
  text(enemySet, 80, 20); 
  text(enemyScore, 160, 20); 
  text(mySet, 320, 20); 
  text(myScore, 400, 20); 
  
  if (myScore > 2) {
    mySet++;
    myScore = 0;
  }
  if (enemyScore > 2) {
    enemySet++;
    enemyScore = 0;
  }
  
  xSpeed += 0.01;
  ySpeed += 0.01;
  
  textSize(80);
  if (enemySet >= 3){
    text("You LOSE!", width/2, 130);
    textSize(40);
    text("Click to restart", width/2, 200);
  }
  else if (mySet >= 3){
    text("You WIN!", width/2, height/2-30);
    textSize(40);
    text("Click to restart", width/2, height/2+30);
  }
  
  if(mousePressed){
    ballX = width/2;
    ballY = height/2;
    mySet = 0;
    myScore = 0;
    enemySet = 0;
    enemyScore = 0;
    xSpeed = 1;
    ySpeed = 1;
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *