LoginSignup
3
3

More than 5 years have passed since last update.

Firebaseハンズオン@クラウドごった煮福島

Last updated at Posted at 2015-09-26

Firebaseの準備

https://www.firebase.com/
①「signup」をクリック
②「Email」「Password」を入力して「Create My Account」
③とりあえず既に「MY FIRST APP」が用意されているのでその「Manage App」をクリック

Cloud9の準備

https://c9.io/
①「signup」をクリック→必要事項を入力してsignup
②「Go to your dashboard」をクリック
③「Create a new workspace」をクリック
④「Workspace name」を入れて、「Create workspace」をクリック

サンプルを見てみよう

チャット

キャラクター診断

リアルタイム通信ゲーム

ソース

チャット

chat.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>チャット</title>
        <script src="https://cdn.firebase.com/js/client/2.3.0/firebase.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
        <form id="input_form">
            <input type="text" id="name" size="10" placeholder="Name" value="名無し">
            <input type="text" id="input_text" size="50">
            <button type="submit" id="send_btn">SEND</button>
            <hr>
            <div id="chat_area"></div>
        </form>
    </body>
    <script>
        $(function(){

            // Firebaseオブジェクトを生成.
            var fb = new Firebase("https://<<yourappid>>.firebaseio.com/");

            // 発言履歴を表示.
            fb.child("chat").on("value", function(snapshot) {
                $("#chat_area").html("");
                $("#input_text").val("");

                var logs = snapshot.val();
                for (var key in logs) {
                    var logHtml = '<p>' + logs[key].name + ':' + logs[key].text + '</p><hr>'
                    $("#chat_area").prepend(logHtml);
                }
            });

            // 発言を送信.
            $("#input_form").submit(function(){
                fb.child("chat").push({
                    name: $("#name").val(),
                    text: $("#input_text").val()
                })
                return false;
            });
        });
    </script>
</html>

キャラクター診断

diagnose.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>ドラゴンボールキャラ診断</title>
        <script src="https://cdn.firebase.com/js/client/2.3.0/firebase.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
        <p id="question"></p>
        <div id="answers"></div>
    </body>
    <script>
        $(function(){

            // 初期化データ.
            var initJson = {
                "Q1": {
                    "question": "かめはめ波が出せる?",
                    "answer": [{"text": "はい", "next": "Q2"}, {"text": "いいえ", "next": "Q5"}]
                },
                "Q2": {
                    "question": "超サイヤ人になれる?",
                    "answer": [{"text": "はい", "next": "Q3"}, {"text": "いいえ", "next": "Q4"}]
                },
                "Q3": {
                    "question": "父親である",
                    "answer": [{"text": "はい", "next": "A1"}, {"text": "いいえ", "next": "A2"}]
                },
                "Q4": {
                    "question": "緑色?",
                    "answer": [{"text": "はい", "next": "A3"}, {"text": "いいえ", "next": "A4"}]
                },
                "Q5": {
                    "question": "戦闘力が53万である",
                    "answer": [{"text": "はい", "next": "A5"}, {"text": "いいえ", "next": "Q6"}]
                },
                "Q6": {
                    "question": "ビッグバンアタックなら出せる",
                    "answer": [{"text": "はい", "next": "A6"}, {"text": "いいえ", "next": "A7"}]
                },
                "A1": "あなたは孫悟空です。",
                "A2": "あなたは孫悟飯です。",
                "A3": "あなたはセルです。",
                "A4": "あなたは亀仙人です。",
                "A5": "あなたはフリーザです。",
                "A6": "あなたはベジータです。",
                "A7": "あなたはヤムチャです。"
            }

            // Firebaseオブジェクトを生成.
            var fb = new Firebase("https://<<yourappid>>.firebaseio.com/");

            viewQuestion("Q1");

            // 質問を表示.
            function viewQuestion(pickNode) {
                fb.child("diagnose/" + pickNode).on("value", function(snapshot) {
                    var data = snapshot.val();

                    if (pickNode == "Q1" && !data) {
                        // 質問データが入ってなかったら初期データを登録する.

                        fb.child("diagnose").set(initJson);
                    } else if (data.question) {

                        // 質問と選択肢を表示する.
                        $("#question").text(data.question);

                        var ansBtnsHtml = "";
                        for (var i in data.answer) {
                            ansBtnsHtml += '<button class="ans-btn" value="' + data.answer[i].next + '">' + data.answer[i].text + '</button>';
                        }
                        $("#answers").html(ansBtnsHtml);
                    } else {

                        // 診断結果を表示する.
                        $("#question").html(data);
                        $("#answers").html('<button id="back_btn">戻る</button>');
                    }
                });
            }

            // 選択肢をクリックした時、次の質問または診断結果を表示する.
            $(document).on("click", ".ans-btn", function(){
                viewQuestion($(this).val());
            });

            // 戻るボタンクリックで初めの質問に戻る.
            $(document).on("click", "#back_btn", function(){
                viewQuestion("Q1");
            });
        });
    </script>
</html>

リアルタイム通信ゲーム

battle.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>なかぞのバトル</title>
        <script src="https://cdn.firebase.com/js/client/2.3.0/firebase.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
        <button id="add_btn">増殖</button>
        <div id="battle_area"></div>
    </body>
    <script>
        $(function(){

            // Firebaseオブジェクトを生成.
            var fb = new Firebase("https://<<yourappid>>.firebaseio.com/");

            var intervalMap = new Object();

            // nakazonoがFirebaseに追加されたとき、顔を表示.
            fb.child("zono").on("child_added", function(snapshot, key) {

                var imgSrc = snapshot.val();
                var imgKey = snapshot.key();
                console.log(imgSrc);

                var zonoEl = document.createElement("a");
                $(zonoEl).addClass("zono").attr("href", "#").attr("data-index", imgKey);
                $(zonoEl).css("top", random(600));
                $(zonoEl).css("left", random(800));
                $(zonoEl).append('<img src="./img/' + imgSrc + '"/>');
                $("#battle_area").append(zonoEl);
                moveZono(zonoEl, imgKey);
            });

            // nakazonoがFirebaseから削除されたとき、対応する顔を消す.
            fb.child("zono").on("child_removed", function(snapshot){
                var removeKey = snapshot.key();
                clearInterval(intervalMap[removeKey]);
                $(".zono[data-index=" + removeKey + "]").remove();
            });

            // nakazonoを増やす.
            $("#add_btn").click(function(){
                fb.child("zono").push("zono" + (random(3) + 1) + ".png");
            });

            // 顔にカーソルが触れた時、nakazonoを消去する.
            $(document).on("mouseover", ".zono", function(){
                var thisIdx = $(this).attr("data-index");
                fb.child("zono/" + thisIdx).remove();
            });

            // nakazonoをランダムに動かす.
            function moveZono(el, index) {

                intervalMap[index] = setInterval(function(){
                    var top = Number($(el).css("top").replace("px", ""));
                    var left = Number($(el).css("left").replace("px", ""));

                    // 上下方向の移動距離を算出.
                    var topAdd = random(30);
                    if (random(2) == 0) topAdd = -1 * topAdd;

                    if ((top + topAdd) < 0 || (top + topAdd) > 600) {
                        topAdd = 0;
                    }

                    // 左右方向の移動距離を算出.
                    var leftAdd = random(30);
                    if (random(2) == 0) leftAdd = -1 * leftAdd;

                    if ((left + leftAdd) < 0 || (left + leftAdd) > 800) {
                        leftAdd = 0;
                    }

                    $(el).css("top", top + topAdd);
                    $(el).css("left", left + leftAdd);
                }, 200);

            }

            // 乱数を生成する.
            function random(num) {
                return Math.floor( Math.random() * num);
            }
        });
    </script>
    <style>
        #battle_area {
            postion: relative;
            width: 800px;
            height: 600px;
            background: #f3f3f3;
        }
        .zono {
            position: absolute;
        }
        .zono img {
            width: 50px;
        }
    </style>
</html>

動かしてみよう

var fb = new Firebase("https://<<yourappid>>.firebaseio.com/");
<>の部分を自分のFirebaseのIDに変える。

Firebaseデプロイ

①Cloud9のBashタブを選択
②コマンド実行
 npm install -g firebase-tools
③コマンド実行
 firebase init
 Firebaseの登録に使ったメールアドレス、パスワードを入力
 FirebaseのappIdを指定
 Public Directory →エンター
④コマンド実行
 firebase deploy
 Site URLにアクセス!

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