スマレジエンジニアyushiのブログ

スマレジエンジニアのブログ

【将棋盤 第3回】駒を動かす

引き続き将棋盤を作っていきます。

使用技術は下記の通りです。

  • Vue.js3
  • Vite
  • SCSS

今回は、駒を動かす機能を作成します。

駒台を用意する

駒の一覧から、先手・後手それぞれの駒台の置かれる駒と、その数を抜き出すcomputed propertyを用意します。

const reduceStandPieces = (carry, piece) => {
  const c = carry.find((p) => p.type === piece.type)
  if (c) {
    c.count += 1
  } else {
    carry.push({
      type: piece.type,
      name: piece.name,
      count: 1,
    })
  }
  return carry
}

computed: {
    firstStandPieces() {
      return this.pieces
        .filter((piece) => piece.isFirst)
        .filter((piece) => piece.column === null)
        .reduce(reduceStandPieces, [])
    },
}

v-forでループして並べます。

    <div class="stand first-stand">
      <div v-for="p in firstStandPieces" :key="p.type" class="stand-piece">
        <span class="stand-piece-name">{{ p.name }}</span>
        <span class="stand-piece-count">{{ p.count }}</span>
      </div>
    </div>

駒の名前と数は、inline-flexで配置します。

.stand {
  width: 70px;
  height: 400px;
  border: $board-border-width solid $border-color;
}
.stand-piece {
  display: inline-flex;
  align-items: center;
  height: 50px;
}

駒を動かす

駒を動かすロジックを用意します。

駒のあるマスをclickするとselectPiece、駒のないマスをclickするとselectBoxが発火します。

駒を動かすロジックが、movePieceです。

    selectBox(column, row) {
      if (this.selected) {
        this.selected.column = column
        this.selected.row = row
        this.movePiece(this.selected, column, row)
      }
    },
    selectPiece(id) {
      const piece = this.pieces.find((p) => p.id === id)
      if (this.isFirst === piece.isFirst) {
        this.selectedId = id
        return
      }
      if (!this.selected) {
        return
      }
      this.movePiece(this.selected, piece.column, piece.row, piece)
    },
    movePiece(piece, column, row, captured = null) {
      if (captured) {
        captured.isFirst = this.isFirst
        captured.column = null
        captured.row = null
      }
      piece.column = column
      piece.row = row
      this.lastMovedPieceId = piece.id
      this.isFirst = !this.isFirst
      this.selectedId = null
    },

完成した画面

選択中の駒はオレンジ色、最後に動かした駒は赤色になっています。

なお、戦型は角交換四間飛車です(駒台に乗せるため、早々に角を交換する戦型)。

f:id:yushi0:20210227180835p:plain

ソースコード

https://github.com/nek0meshi/shogi-board/pull/3

まとめ

駒が動いてだんだん将棋が指せそうな感じが出てきました。

まだ動かす制限や勝利判定はできていませんので、それは今後。