ToroVerse

クラス④ 既存のスケッチをクラスに書き直す

この回でできるようになること

クラスの書き方を知っていることと、自分のプログラムをクラスで書けることの間には、少し距離があります。この回では、変数と if だけで書いた「跳ね返るボール」のプログラムを、1歩ずつ、クラスを使った形に書き直していきます。

sketch.js
let ball1;
let ball2;
let ball3;

function setup() {
  createCanvas(400, 400);
  ball1 = new Ball(100, 150, 3, 2, 25);
  ball2 = new Ball(300, 100, -2, 4, 40);
  ball3 = new Ball(200, 300, 5, -1, 15);
}

function draw() {
  background(220);
  ball1.update();
  ball1.show();
  ball2.update();
  ball2.show();
  ball3.update();
  ball3.show();
}

class Ball {
  constructor(x, y, speedX, speedY, r) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.r = r;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;

    if (this.x > width - this.r) {
      this.speedX = -this.speedX;
    }
    if (this.x < this.r) {
      this.speedX = -this.speedX;
    }
    if (this.y > height - this.r) {
      this.speedY = -this.speedY;
    }
    if (this.y < this.r) {
      this.speedY = -this.speedY;
    }
  }

  show() {
    circle(this.x, this.y, this.r * 2);
  }
}

3つのボールが、それぞれ壁で跳ね返りながら動いています。これが、この回の終わりにできあがるプログラムです。


この回が終わると、次のことができるようになります。

  • プログラムの中から、クラスにまとめられる部分を見つける
  • 変数をプロパティに、処理をメソッドに、移し替える
  • 書き直したあとで、動きが変わっていないことを確かめる
  • 何をプロパティにし、何をメソッドにするかを、自分で決める

出発点:変数で書いた、跳ね返るボール

書き直す前の、もとのプログラムです。

sketch.js
let x = 100;
let y = 150;
let speedX = 3;
let speedY = 2;
let r = 25;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  circle(x, y, r * 2);

  x += speedX;
  y += speedY;

  if (x > width - r) {
    speedX = -speedX;
  }
  if (x < r) {
    speedX = -speedX;
  }
  if (y > height - r) {
    speedY = -speedY;
  }
  if (y < r) {
    speedY = -speedY;
  }
}

ボールが1つ、4つの壁で跳ね返ります。位置 x・y、速度 speedX・speedY、半径 r の、5つの変数を使っています。


このプログラムは、正しく動きます。ボールが1つだけなら、これで十分です。

ボールを増やそうとすると

ここに、ボールをもう1つ足したくなったとします。同じ書き方で足すと、こうなります。

javascript
let x1 = 100;
let y1 = 150;
let speedX1 = 3;
let speedY1 = 2;
let r1 = 25;

let x2 = 300;
let y2 = 100;
let speedX2 = -2;
let speedY2 = 4;
let r2 = 40;

変数が、10 個になりました。draw の中も、circle が2つ、位置を動かす行が4つ、if が8つになります。


ボールが3つなら変数は 15 個、if は 12 個です。同じ形の行が、数字を変えただけで、何度も繰り返されます。speedX1 と書くべきところを、1か所だけ speedX2 と書き間違えても、エラーにはなりません。片方のボールが、もう片方の動きに合わせて、おかしな跳ね返り方をするだけです。


「同じ種類のものを、いくつも作りたい」。これが、クラスに書き直す、いちばんの合図です。

書き直しの手順

書き直しは、次の5つの段階で進めます。一度に全部を変えず、1段階ごとに実行して、動くことを確かめます。

  1. 変数を見つける。 ボールに関係する変数を、すべて挙げる
  2. 処理を見つける。 ボールに関係する処理を、役割ごとに分ける
  3. クラスの枠を作る。 変数を、constructor の中のプロパティにする
  4. 処理を、メソッドに移す。 変数の名前に、this. を付ける
  5. 使う側を書き換える。 new でインスタンスを作り、メソッドを呼び出す

段階1:変数を見つける

もとのプログラムの変数を、「ボールに関するものか」で分けます。

変数 意味 ボールに関するものか
x、y ボールの位置 はい
speedX、speedY ボールの速度 はい
r ボールの半径 はい
width、height キャンバスの大きさ いいえ

x、y、speedX、speedY、r の5つは、ボールが違えば、値も違うものです。これらが、クラスのプロパティになります。


width と height は、キャンバスの大きさです。ボールが何個あっても、同じ値を使います。これは、ボールのものではないので、プロパティにはしません。


見分けるときの問いは、「ボールが2つになったら、この値も2つ必要になるか」です。必要になるなら、プロパティです。

段階2:処理を見つける

次に、draw の中の処理を、役割ごとに分けます。

処理 役割
background(220); 画面全体を消す
circle(x, y, r * 2); ボールを描く
x += speedX; と y += speedY; ボールを動かす
4つの if 壁で跳ね返す

background は、画面全体に関する処理です。ボールが何個あっても、1回だけ実行すれば済みます。これは、クラスには入れず、draw に残します。


残りの3つは、どれも、ボール1つ1つについて行う処理です。これらが、クラスのメソッドになります。

  • 「描く」→ show メソッド
  • 「動かす」と「跳ね返す」→ update メソッド

動かすことと、跳ね返すことは、どちらも「ボールの状態を、次のフレームのために変える」処理なので、1つの update にまとめます。

段階3:クラスの枠を作る

クラスを書き始めます。まず、段階1で見つけた5つの変数を、constructor の中のプロパティにします。


もとの宣言と、プロパティを見比べます。

もとの変数の宣言 プロパティ
let x = 100; this.x = x;
let y = 150; this.y = y;
let speedX = 3; this.speedX = speedX;
let speedY = 2; this.speedY = speedY;
let r = 25; this.r = r;

ボールごとに違う値にしたいので、5つとも、constructor の引数で受け取ります。

javascript
class Ball {
  constructor(x, y, speedX, speedY, r) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.r = r;
  }
}

もとのプログラムで、宣言のときに入れていた 100、150、3、2、25 という数字は、クラスの中には書きません。これらは、「このボール」の値であって、「ボールというもの」の決まりではないからです。数字は、あとで new のときに渡します。

段階4:処理を、メソッドに移す

段階2で分けた処理を、メソッドとして、クラスの中へ移します。

描く処理を、show に移す

もとの行は、これです。

javascript
circle(x, y, r * 2);

これを、show メソッドの中に書き、ボールの変数の名前に、this. を付けます。

sketch.js
show() {
  circle(this.x, this.y, this.r * 2);
}

変えたのは、x を this.x に、y を this.y に、r を this.r に、の3か所です。それ以外は、1文字も変えていません。

動かす処理と、跳ね返す処理を、update に移す

同じように、残りの処理を update に移し、ボールの変数に this. を付けます。

sketch.js
update() {
  this.x += this.speedX;
  this.y += this.speedY;

  if (this.x > width - this.r) {
    this.speedX = -this.speedX;
  }
  if (this.x < this.r) {
    this.speedX = -this.speedX;
  }
  if (this.y > height - this.r) {
    this.speedY = -this.speedY;
  }
  if (this.y < this.r) {
    this.speedY = -this.speedY;
  }
}

this. を付けたのは、x、y、speedX、speedY、r だけです。width と height には、付けていません。この2つは、ボールのプロパティではなく、p5.js が用意している、キャンバスの大きさだからです。

名前 this. を付けるか 理由
x、y、speedX、speedY、r 付ける このボールのプロパティだから
width、height 付けない キャンバスのもので、ボールのものではないから
circle 付けない p5.js の関数だから

this. の付け忘れと、付けすぎは、書き直しで、いちばん起きやすい間違いです。段階1で作った「ボールの変数の一覧」と照らし合わせながら、1つずつ確かめます。

段階5:使う側を書き換える

クラスができたので、それを使う側、つまり一番上の変数と、setup、draw を書き換えます。

一番上の変数

5つあった変数は、もう要りません。代わりに、インスタンスを入れる変数を、1つ宣言します。

sketch.js
let ball;

setup

setup の中で、インスタンスを作ります。もとのプログラムで、変数の宣言に書いていた数字を、ここで渡します。

sketch.js
ball = new Ball(100, 150, 3, 2, 25);

draw

draw の中の、ボールに関する処理は、すべてメソッドの呼び出しに置き換わります。

sketch.js
function draw() {
  background(220);
  ball.update();
  ball.show();
}

書き直したプログラム

全体を、つなげます。

sketch.js
let ball;

function setup() {
  createCanvas(400, 400);
  ball = new Ball(100, 150, 3, 2, 25);
}

function draw() {
  background(220);
  ball.update();
  ball.show();
}

class Ball {
  constructor(x, y, speedX, speedY, r) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.r = r;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;

    if (this.x > width - this.r) {
      this.speedX = -this.speedX;
    }
    if (this.x < this.r) {
      this.speedX = -this.speedX;
    }
    if (this.y > height - this.r) {
      this.speedY = -this.speedY;
    }
    if (this.y < this.r) {
      this.speedY = -this.speedY;
    }
  }

  show() {
    circle(this.x, this.y, this.r * 2);
  }
}

実行して、もとのプログラムと見比べてください。ボールの動きは、まったく同じです。


これが、書き直しの大事な決まりです。書き直しの目的は、動きを変えずに、書き方だけを整理することです。動きが変わっていたら、どこかで間違えています。

書き直して、何が変わったか

プログラムの行数は、もとより増えました。それでも書き直す価値があるのは、次の2つが変わったからです。

draw が、読みやすくなった

もとのプログラム 書き直したプログラム
draw の中身 circle、位置の計算、4つの if が並ぶ ball.update(); と ball.show(); の2行
読んでわかること 細かい計算の手順 「ボールを更新して、表示する」という流れ

draw を読めば、全体として何をしているかが、すぐにわかります。跳ね返りの細かい仕組みを知りたいときだけ、Ball クラスの中を見れば済みます。

ボールを、簡単に増やせるようになった

ボールを2つ足します。必要なのは、宣言、new、メソッドの呼び出しだけです。

sketch.js
let ball1;
let ball2;
let ball3;

function setup() {
  createCanvas(400, 400);
  ball1 = new Ball(100, 150, 3, 2, 25);
  ball2 = new Ball(300, 100, -2, 4, 40);
  ball3 = new Ball(200, 300, 5, -1, 15);
}

function draw() {
  background(220);
  ball1.update();
  ball1.show();
  ball2.update();
  ball2.show();
  ball3.update();
  ball3.show();
}

class Ball {
  constructor(x, y, speedX, speedY, r) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.r = r;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;

    if (this.x > width - this.r) {
      this.speedX = -this.speedX;
    }
    if (this.x < this.r) {
      this.speedX = -this.speedX;
    }
    if (this.y > height - this.r) {
      this.speedY = -this.speedY;
    }
    if (this.y < this.r) {
      this.speedY = -this.speedY;
    }
  }

  show() {
    circle(this.x, this.y, this.r * 2);
  }
}

Ball クラスは、1文字も変えていません。跳ね返りの if は、4つのままです。3つのボールが、同じ4つの if を、それぞれ自分の位置と速度で使っています。


変数で書いていたら、変数が 15 個、if が 12 個になっていたところです。

クイズ

書き直したプログラムで、跳ね返ったときに、ボールが少しずつ速くなるようにしたいとします。プログラムの、どこを直せばいいでしょう? ボールは3つあります。

▶ 答えを確認する

Ball クラスの update メソッドの中の、4つの if だけです。直すのは、ボールの数に関係なく、1か所です。


速度をひっくり返す行を、-1.05 を掛ける形に変えます。符号が逆になり、大きさが 1.05 倍になります。

javascript
if (this.x > width - this.r) {
  this.speedX *= -1.05;
}

残りの3つの if も、同じように直します。setup と draw は、変えません。3つのボールすべてが、跳ね返るたびに速くなるようになります。


「ボールの振る舞いを変えたいときは、Ball クラスの中だけを見ればいい」。これが、クラスにまとめた効果です。

メソッドを、さらに分ける

update の中には、「動かす」と「跳ね返す」という、2つの仕事が入っています。これを、別々のメソッドに分けることもできます。

sketch.js
let ball;

function setup() {
  createCanvas(400, 400);
  ball = new Ball(100, 150, 3, 2, 25);
}

function draw() {
  background(220);
  ball.update();
  ball.show();
}

class Ball {
  constructor(x, y, speedX, speedY, r) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.r = r;
  }

  update() {
    this.move();
    this.bounce();
  }

  move() {
    this.x += this.speedX;
    this.y += this.speedY;
  }

  bounce() {
    if (this.x > width - this.r) {
      this.speedX = -this.speedX;
    }
    if (this.x < this.r) {
      this.speedX = -this.speedX;
    }
    if (this.y > height - this.r) {
      this.speedY = -this.speedY;
    }
    if (this.y < this.r) {
      this.speedY = -this.speedY;
    }
  }

  show() {
    circle(this.x, this.y, this.r * 2);
  }
}

update は、this.move(); と this.bounce(); を呼び出すだけになりました。同じクラスの別のメソッドを呼び出すときも、this. を付けます。


draw の側は、変えていません。ball.update(); と呼び出しているだけなので、その中が、いくつのメソッドに分かれているかは、関係ないからです。


分けるかどうかは、好みの部分もあります。目安は、「メソッドの名前を見て、中で何をしているかが、すぐにわかるか」です。1つのメソッドが長くなり、複数のことをしていると感じたら、分けることを考えます。

何をプロパティにし、何をメソッドにするか

書き直すとき、いちばん迷うのが、この判断です。目安を、まとめます。

値の置き場所

値の性質 置き場所
インスタンスごとに違い、フレームをまたいで覚えておく プロパティ(this.x)
メソッドの中の、その場の計算で使うだけ メソッドの中の、ただの変数(let)
すべてのインスタンスで共通の、外の世界の値 クラスの外(width など)

たとえば、ボールの直径は、this.r * 2 で、いつでも計算できます。覚えておく必要がないので、プロパティにはせず、使うときに計算します。「ほかのプロパティから計算できる値」は、プロパティにしないほうが、値の食い違いが起きません。

処理の置き場所

処理の性質 置き場所
1つのインスタンスの、プロパティを読んだり変えたりする そのクラスのメソッド
画面全体や、プログラム全体に関する setup や draw

background(220) は、画面全体を消す処理なので、draw に残しました。もし、これを show の中に入れてしまうと、ボールを1つ描くたびに、画面全体が消されます。2つ目のボールを描くとき、1つ目のボールが消えてしまいます。


「これは、このボールだけの話か、それとも全体の話か」。この問いで、置き場所を決めます。

書き直すときの、よくある間違い

this. を付け忘れる

javascript
update() {
  this.x += speedX;   // 間違い:speedX に this がない
}

もとのプログラムから行を移したとき、this. を付け忘れることがあります。speedX is not defined というエラーになります。

古い変数を、消し忘れる

さらに気づきにくいのが、もとのグローバル変数を、消し忘れた場合です。

javascript
let speedX = 3;      // 消し忘れた、古い変数

class Ball {
  update() {
    this.x += speedX;   // エラーにならず、古い変数を使ってしまう
  }
}

一番上に、古い speedX が残っていると、this. を付け忘れても、エラーになりません。プログラムは動きますが、すべてのボールが、同じ古い変数を使ってしまいます。


クラスに移した変数は、一番上から、必ず消します。消してあれば、this. を付け忘れたとき、エラーで気づけます。

一度に、全部を変える

変数を移し、メソッドを書き、使う側も書き換え、最後に実行する。そこで動かないと、どの段階で間違えたのかが、わかりません。


1段階ごとに実行して、確かめます。たとえば、show メソッドだけを先に作り、draw の中の circle を ball.show(); に置き換えて、実行します。動いたら、次に update へ進みます。

やってみよう

次の3つのプログラムを、クラスを使って書き直してください。どれも、書き直したあとに、同じ種類のものを2つ以上作って、動かしてみます。

問題1:ふくらんで、元に戻る泡

javascript
let x = 200;
let y = 200;
let size = 10;
let grow = 1;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  circle(x, y, size);
  size += grow;

  if (size > 150) {
    size = 10;
  }
}
▶ 答えを確認する

変数は x、y、size、grow の4つです。位置と、ふくらむ速さを、引数にしました。size は、どの泡も 10 から始まるので、constructor の中で直接入れています。

sketch.js
let bubble1;
let bubble2;

function setup() {
  createCanvas(400, 400);
  bubble1 = new Bubble(120, 200, 1);
  bubble2 = new Bubble(280, 200, 2.5);
}

function draw() {
  background(220);
  bubble1.update();
  bubble1.show();
  bubble2.update();
  bubble2.show();
}

class Bubble {
  constructor(x, y, grow) {
    this.x = x;
    this.y = y;
    this.size = 10;
    this.grow = grow;
  }

  update() {
    this.size += this.grow;

    if (this.size > 150) {
      this.size = 10;
    }
  }

  show() {
    circle(this.x, this.y, this.size);
  }
}

問題2:右端から出て、左端に戻る雲

javascript
let x = 0;
let y = 100;
let speed = 1;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  circle(x - 30, y + 10, 50);
  circle(x, y, 70);
  circle(x + 30, y + 10, 50);

  x += speed;
  if (x > width + 60) {
    x = -60;
  }
}
▶ 答えを確認する

3つの circle は、まとめて「雲を描く」処理です。すべて show に移します。

sketch.js
let cloud1;
let cloud2;
let cloud3;

function setup() {
  createCanvas(400, 400);
  cloud1 = new Cloud(0, 80, 1);
  cloud2 = new Cloud(200, 180, 0.5);
  cloud3 = new Cloud(100, 300, 2);
}

function draw() {
  background(220);
  cloud1.update();
  cloud1.show();
  cloud2.update();
  cloud2.show();
  cloud3.update();
  cloud3.show();
}

class Cloud {
  constructor(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
  }

  update() {
    this.x += this.speed;

    if (this.x > width + 60) {
      this.x = -60;
    }
  }

  show() {
    circle(this.x - 30, this.y + 10, 50);
    circle(this.x, this.y, 70);
    circle(this.x + 30, this.y + 10, 50);
  }
}

width には、this. を付けません。

問題3:上下に往復する四角形

javascript
let x = 180;
let y = 50;
let speedY = 3;
let size = 40;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  rect(x, y, size, size);
  y += speedY;

  if (y > height - size) {
    speedY = -speedY;
  }
  if (y < 0) {
    speedY = -speedY;
  }
}
▶ 答えを確認する
sketch.js
let box1;
let box2;

function setup() {
  createCanvas(400, 400);
  box1 = new Box(80, 50, 3, 40);
  box2 = new Box(250, 200, -5, 80);
}

function draw() {
  background(220);
  box1.update();
  box1.show();
  box2.update();
  box2.show();
}

class Box {
  constructor(x, y, speedY, size) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
    this.size = size;
  }

  update() {
    this.y += this.speedY;

    if (this.y > height - this.size) {
      this.speedY = -this.speedY;
    }
    if (this.y < 0) {
      this.speedY = -this.speedY;
    }
  }

  show() {
    rect(this.x, this.y, this.size, this.size);
  }
}

rect の座標は左上の角を指すので、下の壁との判定は height - this.size、上の壁との判定は 0 です。もとのプログラムの条件を、そのまま移しています。

まとめ

  • 同じ種類のものを、いくつも作りたくなったら、クラスに書き直す合図
  • 書き直しは、「変数を見つける → 処理を見つける → クラスの枠を作る → メソッドに移す → 使う側を書き換える」の順に進める
  • 「ボールが2つになったら、この値も2つ必要になるか」で、プロパティにするかを決める
  • メソッドに移すとき、インスタンスの変数には this. を付ける。width や circle のような、外のものには付けない
  • 画面全体に関する処理(background など)は、クラスに入れず、draw に残す
  • 書き直しの目的は、動きを変えずに、書き方を整理すること。書き直したら、同じ動きになっているかを確かめる
  • クラスに移した変数は、一番上から消す。消し忘れると、this. の付け忘れに気づけなくなる
  • 1段階ごとに実行して、確かめる