1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Processing&Java] 数字を順番に引いていくやつ…

Posted at

問題

 研究室の学生から,「もとの数から交互に1〜3の数字を順番に引いていって先に0にできた人が勝ちというゲームのプログラムを作りたいんですが…」というお悩み相談を受けた。これに似たルールはいろいろとあるがゲームの名前が思いつかない(苦笑)。それ自体は大したことではないがちょっともどかしい。
 単純なゲームであるが,まだ,Javaのプログラミングを始めたばかりの学生なので,実装は難しいのかなとも思ったが,その難しさの原因としては,

  1. ユーザインタフェースの作り込みでつまづいている
  2. アルゴリズムの検討でつまづいている
  3. データの扱い方でつまいている
    などが考えられそうである。

とにかく書いてみる

 1点目のつまづきは,その学生が最初からNetBeansなどの本格的なIDEを使っていることにも原因がありそうだ。まずは,小学生からでも使えるScratchなどのビジュアルプログラミング言語などでもよいが,JavaであればとProcessingを勧めた。

int keyIndex = -1;

int goal = 20;

void setup() {
  size(320, 200);
  noStroke();
  background(0);
}

void draw() { 
  // keep draw() here to continue looping while waiting for keys
}

void keyPressed() {
  if (key < '1' || key > '3') {
    // error
    keyIndex = -1;
  } else {
    keyIndex = key - '0';
  }

  if (keyIndex > -1) {
    int remain = goal - keyIndex;
    int cmpchoose = 0;

    println("you choose = ", keyIndex);
    println("current number = ", remain);
    if (remain == 0) {
      println("YOU WIN!!");
      goal = 30;
      println("PLAY AGAIN!!");
      println("-----");
    } else {
      println("-----");
      if (remain < 3) {
        cmpchoose = (int)random(1, remain);
      } else {
        cmpchoose = (int)random(1, 3);
      }

      println("computer choose = ", cmpchoose);
      remain -= cmpchoose;
      println("current number = ", remain);
      if (remain == 0) {
        println("YOU LOSE!!");
        goal = 30;
        println("PLAY AGAIN!!");
      }
      println("-----");
      goal = remain;
    }
  }
}
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?