日常の進捗

主に自分のための,行為とその習慣化の記録

Mod:Coding Challenge #31: Flappy Bird

横スクロールゲーム「Flappy Bird」ライクなものを作る.画面をクリックしてからスペースキーを叩くと,ボール(鳥)が羽ばたく.それで左から流れてくる土管を避ける.スコア機能や色をつけるなど実装した.暇な時にパソコンで遊んでください.

コード

Bird bird;
ArrayList<Pipe> pipes;
float currentTime;
float lastHitMills;
int score;
int highScore;

void setup() {
  fullScreen();
  colorMode(HSB, 360, 100, 100);
  bird = new Bird();
  pipes = new ArrayList<Pipe>();
  pipes.add(new Pipe());

  lastHitMills = 0;
  score = 0;
  highScore = 0;
}

void draw() {
  background(220, 60, 80);
  currentTime = millis();
  score = int(currentTime - lastHitMills)/10;
  highScore = max(score, highScore);
  textAlign(LEFT, CENTER);
  textSize(24);
  fill(0, 0, 100);
  text("現在のスコア :"  +  int(score-1), 40, 40);
  text("ハイスコア :"  +  int(highScore-1), 40, 65);

  for (int i = pipes.size()-1; i > 0; i--) {
    Pipe p = pipes.get(i);
    p.update();
    p.draw();
    if (p.isHit(bird)) {
      lastHitMills = millis();
    }
    if (p.isOffScreen()) {
      pipes.remove(i);
    }
  } 
  bird.update();
  bird.checkBound();
  bird.draw();

  if (frameCount % 33 == 0) {
    pipes.add(new Pipe());
  }
}

void keyPressed() {
  if (key == ' ') {
    bird.fly();
  }
}

class Bird {
  PVector pos;
  PVector vel;
  PVector acc;
  Bird() {
    pos = new PVector(width / 10, height/2);
    vel = new PVector(0, 0);
    acc = new PVector(0, 0.6);
  }

  void update() {
    vel.add(acc);
    pos.add(vel);
  }
  void checkBound() {
    if (pos.y > height) {
      pos.y = constrain(pos.y, 0, height);
      vel.y = 0;
      lastHitMills = millis();
    }
  }

  void draw() {
    fill(40, 80, 100);
    ellipse(pos.x, pos.y, 32, 32);
  }

  void fly() {
    vel = new PVector(0, -7.5);
  }
}

class Pipe {
  float top;
  float bottom;
  float x;
  float w;
  float speed;
  boolean highLight;
  Pipe() {
    top = random(height/2);
    bottom = random(height/2);
    x = width;
    w = 20;
    speed = 7.5;
    highLight = false;
  }

  void update() {
    x -= speed;
  }

  void draw() {
    noStroke();
    if (highLight) {
      fill(0, 100, 100);
    } else {
      fill(0, 0, 100);
    }
    rect(x, 0, w, top);
    rect(x, height-bottom, w, bottom);
  }
  boolean isHit(Bird b) {
    if (bird.pos.y < top || bird.pos.y > height - bottom) {
      if (bird.pos.x > x && bird.pos.x < x + w) {
        background(60, 100, 100);
        highLight = true;
        textAlign(CENTER, CENTER);
        textSize(200);
        fill(0, 100, 100);
        text("HIT!!!", width/2, height/2);
        return true;
      }
    }      
    return false;
  }
  boolean isOffScreen() {
    if (x  < - w) {
      return true;
    } else {
      return false;
    }
  }
}

リファレンス