タイルゲームを作ってみる


はじめに

パズドラみたいな動きを実装してみたいと思い、タイルゲーム的なものを作ってみました。得点などのゲーム的な要素がまったく実装できていないので、ゲームとは名ばかりですが、ころころとタイルを動かしてみると、なんとなく和みます。

今回紹介する内容は、前々回のパレットを作ってみるで紹介した内容を利用すると、より楽しめるかと思います。いつものように、どんなものをつくったか?どのようにつくったか?を書いてみたいと思います。

どんなものをつくったか

どうやってつくったか

まず、次のコマンドを実行します。

$ rbenv exec rails new tilegame
$ cd tilegame
$ rbenv generate controller Bingo sample

次に、実装を追加します。まずはビューから実装します。

sample.html.erb
<h1>Bingo#sample</h1>
<p>Find me in app/views/bingo/sample.html.erb</p>

<table id="board" style="border-collapse: collapse">
    <tr>
        <td style="background: #F00; width: 50px; height: 50px"></td>
        <td style="background: #0F0; width: 50px; height: 50px"></td>
        <td style="background: #00F; width: 50px; height: 50px"></td>
    </tr>
    <tr>
        <td style="background: #FF0; width: 50px; height: 50px"></td>
        <td style="background: #F0F; width: 50px; height: 50px"></td>
        <td style="background: #0FF; width: 50px; height: 50px"></td>
    </tr>
    <tr>
        <td style="background: #000; width: 50px; height: 50px"></td>
        <td style="background: #FFF; width: 50px; height: 50px"></td>
        <td style="background: #F0F0F0; width: 50px; height: 50px"></td>
    </tr>
</table>

次にマウスのポインタが画像の上に移動したときの動きを実装します。

bingo.js.coffee
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/

class Board
  _onBoard: null
  _oldStyle: null

  _exchange: (newtd) ->
    $oldtd = $("#board td").filter("[style = \"" + @_oldStyle + "\"]")
    newStyle = $(newtd).attr("style")
    $(newtd).attr("style", @_oldStyle)
    $oldtd.attr("style", newStyle)

  _execute: (self, td) ->
      if self._oldStyle?
        self._exchange(td)

  _eventify: ->
    $("#board").hover =>
      @_onBoard = true
    , =>
      @_onBoard = false
      @_oldStyle = null

    self = this

    $("#board td").hover ->
      self._execute(self, @)
      self._oldStyle = $(@).attr("style")
    , ->
    @

  constructor: ->
    @_eventify()

# main
$ ->
  board = new Board()

# /* vim: set sw=2 sts=2 et : */

まとめ

テトリスやぷよぷよみたいな動きを実装できれば、もっとよくなりそうです。