LoginSignup
18
9

More than 5 years have passed since last update.

Vue.jsでテトリスを作成してみた

Last updated at Posted at 2019-01-16

はじめに

npmやVueは導入済みの前提で進めていきます。
あまりVueを使ったテトリスの記事がなかったので今回書いてみました。

環境

下記の環境で実施しております。

OS: macOS High Sierra 10.13.6
Vue: 2.9.6
node: v10.7.0
npm: 6.2.0

内容

Githubに公開しております。
簡単にロジック周りを下記で記載しておりますが、
上記のリポジトリをみていただければ把握できるかと思います。

あまり時間を割いて作成しておりませんので、不備等ございましたら、
ご連絡いただければ、と思います。

ロジック/UI周り

1. 見た目

CSSが苦手なので、Buefyを使用して、ある程度見た目を整えております。
例:スタート時のモーダル画面
”b-”で始まるコンポーネントがbuefyで使われるコンポーネントとなります。
また、CSSフレームワークであるbulmaの派生のため、
button や is-infoなどをクラスで定義可能です。

Main.vue
<b-modal :active.sync="startFlg"
         :canCancel="false">
  <button class="button is-info is-large"
          @click="startFlg=false; start()">Game Start</button>
</b-modal>

2. 描画

SetIntervalを使って描画をしていきます。
draw関数で実際に描画処理を行なっております。

Main.vue
draw () {
  this.init()
  for (var b in this.block) {
    console.log('draw b: ' + this.block[b].x + ', ' + this.block[b].y + ', ' + this.gameTable[this.block[b].y][this.block[b].x])
    if (this.gameTable[this.block[b].y][this.block[b].x] === 0) {
      console.log('draw: ' + this.block[b].x + ', ' + this.block[b].y)
      this.gameTable[this.block[b].y].splice(this.block[b].x, 1, 1)
    }
  }
}

3.ブロックの移動

move関数を作り、x座標、y座標を引数に移動を行なっていきます。
また、移動中のブロックを”1”で定義しております。

Main.vue
move (x, y) {
  this.init()
  for (var b in this.block) {
    this.block.splice(b, 1, {x: this.block[b].x + x, y: this.block[b].y + y})
  }
}

4.ブロックの設置

spliceを使って、”2”をセットし、ブロックが設置されたことを明示します。

Main.vue
setBlock () {
  this.init()
  for (var b in this.block) {
    console.log('setBlock: ' + this.block[b].x + ', ' + this.block[b].y)
    this.gameTable[this.block[b].y].splice(this.block[b].x, 1, 2)
  } 
}

5. ブロックを消す

”2”となっているものが、設置されているブロックを意味していて、
それが一列に並んだ時に消す処理を行います。
unshiftを使って削除処理をおこないます。

Main.vue
clearLine () {
  var line = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
  var clearLine = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  for (var y = 0; y < this.gameTable.length; y++) {
    if (this.arrayCheck(this.gameTable[y], line)) {
      this.gameTable.splice(y, 1)
      this.gameTable.unshift(clearLine)
      this.score += 100
      this.level -= 5
    }
  }
}

実行結果

消した後の描画や、操作周りがまだまだバギーではありますが、下記のような形となりました。
時間がありましたらFixしていきたいと思います。

t.gif

18
9
0

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
18
9