LoginSignup
1
1

More than 5 years have passed since last update.

RailsでDXOpalを使ってみた

Last updated at Posted at 2018-09-27

はじめに

DXOpalというブラウザで動作するゲームライブラリをRailsで動かしてみたときの備忘録です。

dxopalonrails.gif

やったこと

Railsアプリの作成

まず、rails newでアプリのひな型を作成

rails new dxopal_rails --webpack=vue

今後、SPAやPWAにすることも考慮に入れて、--webpack=vueを追加している。

あとは、実際のゲーム画面を表示するviewcontrollerを作成。

rails g controller game index

その後、作成したgame_controller.rbを下記のように修正。

game_controller.rb
class GameController < ApplicationController
  def index
  end

  def main
    main = File.open('./app/views/game/main.rb')
    source = main.read
    render json: source
  end
end

mainというメソッドを追加し、そこでゲームのソースコードを読み取ってJSON形式で展開させている。

最後に、routes.rbを編集して、game/mainへのルーティングを設定する。

routes.rb
Rails.application.routes.draw do
  get 'game/index'
  get 'game/main'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

とりあえず、これでDXOpalが動くひな型はできた。
次に、DXOpalの導入を行う。

DXOpalの導入

まず、gem install dxopalDXOpalをインストール。

gem install dxopal

次に、app/views/gameディレクトリまで移動し、dxopal initを実行する。

dxopal init

その際、index.htmldxopal.min.jsmain.rbが作成される。
index.htmlの中身をindex.html.erb内に貼り付けて、以下のようにする

index.html.erb
<h1>Game#index</h1>
<p>Find me in app/views/game/index.html.erb</p>

    <script type="text/ruby">
      DXOpal.dump_error{ require_remote 'main' }
    </script>

    <canvas id="dxopal-canvas"></canvas>
    <div id="dxopal-errors"></div>

dxopal.min.jsapp/assets/javascript内へ移動させて、application.jsを以下のように書き換える。

application.js
//= require rails-ujs
//= require activestorage
//= require dxopal.min
//= require turbolinks
//= require_tree .

最後に、DXOpalGemfileに追加し、bundle installを行う。
僕の場合、thorのバージョンでエラーが起きていたので、下記のように修正し、bundle updatebundle install をそれぞれ実行したね。

Gemfile
gem 'dxopal'
gem 'thor', '>= 0.19.1'

おわりに

最後に、Railsのサーバーを建てればOK!

rails s

これでDXOpalをRails上で実行できるようになった。

このとき作ったサンプルはこちらからダウンロードできる。
DXOpalOnRails

参考資料

yhara/dxopal

https://yhara.github.io/dxopal/

1
1
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
1
1