4

I'm trying to make a "FourConnect"-game with javascript. I want, that there is a list from all online users. This list I've made with the example on the firebase site. Now I want that I can choose one online user and send them a invitation to play with me. So I wrote a function, that all users expect of me have an additional div. When I click on the div this special user should get a confirm box to say okey or cancel. If the user clicks okey the play should begin. I'll save the name and the id from the user. This already works.

My problem is, that I don't know how to send the request to the other user. I tried out many but always the confirm box is on my brwoser not on the browser of the other user.

I looked for solutions on the firebase page and in google but couldn't find anything which solves my problem.

The code I already have:

  var name = prompt("Your name?", "Guest"),
      currentStatus = "★ online";

  // Get a reference to the presence data in Firebase.
  var userListRef = new Firebase(connectFour.CONFIG.firebaseUrl);

  // Generate a reference to a new location for my user with push.
  var myUserRef = userListRef.push();
  var gameId = myUserRef.name();
  document.getElementById('labelGameId').innerHTML = gameId;

  beginGame({id: gameId, name: name, status: currentStatus});
  // Get a reference to my own presence status.
  var connectedRef = new Firebase('http://presence.firebaseio-demo.com/.info/connected');
  connectedRef.on("value", function(isOnline) {
    if (isOnline.val()) {
      // If we lose our internet connection, we want ourselves removed from the list.
      myUserRef.onDisconnect().remove();

      // Set our initial online status.
      setUserStatus("★ online");
    } else {

      // We need to catch anytime we are marked as offline and then set the correct status. We
      // could be marked as offline 1) on page load or 2) when we lose our internet connection
      // temporarily.
      setUserStatus(currentStatus);
    }
  });
//}


  // A helper function to let us set our own state.
  function setUserStatus(status) {
    // Set our status in the list of online users.
    currentStatus = status;
    myUserRef.set({ name: name, status: status });
  }

  // Update our GUI to show someone"s online status.
  userListRef.on("child_added", function(snapshot) {
    var user = snapshot.val();
    $("#output").append($("<div/>").attr("id", snapshot.name()));
    $("#" + snapshot.name()).text(user.name + " is currently " + user.status);
    if(snapshot.name() != myUserRef.name()){
        var $invite = $('<div id="invite">invite</div>');
        $("#output").append($invite);
        $($invite).on('click', function(){
            //startGame(user);
            console.log('Gegner2: '+snapshot.name());
            console.log('Genger2Name: '+user.name);
                joinGame({id: snapshot.name(), name: user.name, status: user.status});
        });
    }

  });

  // Update our GUI to remove the status of a user who has left.
  userListRef.on("child_removed", function(snapshot) {
    $("#" + snapshot.name()).remove();
  });

  // Update our GUI to change a user"s status.
  userListRef.on("child_changed", function(snapshot) {
    var user = snapshot.val();
    $("#" + snapshot.name()).text(user.name + " is currently " + user.status);
  });
  document.onIdle = function () {
    setUserStatus("☆ idle");
  }
  document.onAway = function () {
    setUserStatus("☄ away");
  }
  document.onBack = function (isIdle, isAway) {
    setUserStatus("★ online");
  }

  setIdleTimeout(5000);
  setAwayTimeout(10000);


function joinGame(opponent) {
    console.log(opponent);
    console.log(opponent.id);
    var player2ID = opponent.id; 
    myUserRef = new Firebase(connectFour.CONFIG.firebaseUrl + opponent.id);
    myUserRef.once('value', function(dataSnapshot){
        if(dataSnapshot.val()){
            beginGame({id: player2ID , name: opponent.name, status: opponent.status});
        }else{
            alert("game doesn't exist");
        }
    });

}

function beginGame(player) {
    console.log(player);
    console.log('Id spieler1: '+gameId);

    });

With this code I can click on "invite" and then I will see the ID which the user had. I also wanted to send the ID to beginGame() but this doesn't really works.

My Firebase Structure:

games

-InmydEpSe5oZcLZUhfU

-InrLM6uxAsoOayOgFce

  -name: "Barbara"

  -status: "away"
user2090392
  • 51
  • 1
  • 1
  • 3
  • Some code or a working example would help quite a bit. Also, a diagram of your Firebase structure would go quite a long ways to explaining what you need. Most importantly, are you picking a random user or do you already know the user's ID? – Kato Feb 20 '13 at 14:45
  • I edited my question. Hope it will help you to understand my problem. – user2090392 Feb 20 '13 at 16:21
  • > see demo here => [Push notification with Firebase](http://stackoverflow.com/questions/37814710/ios-or-objective-c-or-iphone-implementation-push-notification-with-firebase-best) – Sanandiya Vipul Jun 14 '16 at 14:28
  • see demo here= > [Push Notification with Firebase](http://stackoverflow.com/questions/37814710/ios-or-objective-c-or-iphone-implementation-push-notification-with-firebase-best) – Sanandiya Vipul Jun 14 '16 at 14:29
  • http://codingaffairs.blogspot.com/2016/06/firebase-cloud-messaging-push.html – Developine Jun 20 '16 at 08:00

2 Answers2

7

In order to send a message to another user, you need that user to be monitoring a known location in your Firebase. Then when you want to send them a message, you simply modify that location in some way and they'll get a callback. Here's some pseudo code:

var root = new Firebase(...);

//On initialization start listening for messages
root.child("users/inbound-messages").on("child_added", 
  function(newMessageSnapshot) {
    displaySomethingToTheUser(newMessageSnapshot.val());
    newMessageSnapshot.ref().remove();
  }
);

//Send a message to another user
root.child(otherUserId).child("inbound-messages").push("Hi other user!");
Andrew Lee
  • 10,127
  • 3
  • 46
  • 40
  • 1
    Out of interest, why do `newMessageSnapshot.ref().remove();`? – KnewB Jun 09 '14 at 14:32
  • @Andrew Lee If I set up FCM within an app that allows two users to send and receive data to each other, are there any $ costs for me the developer or for the users? If not, Google is basically allowing my app users to access Google's servers for free, to exchange the data? – AJW Sep 02 '18 at 03:21
1

From what I understand. You want a chat window in the game so that users logged to communicate among themselves, okay?

Well, in its structure, you simply add something like:

-Games
    -rooms
     -charOfRoomSpecific
         - users
            
             + InmydEpSe5oZcLZUhfU

              -InrLM6uxAsoOayOgFce
                     name: "Barbara"
                     status "away"
         
       - messages
           + InmyBlaBlae5oZcLPKSu
           -InmyBlaBlae5oZcLPKSu2
                user: "Barbara"
                say: "Hello man, will gamer!"


     + charOfRoomSpecific2
     + charOfRoomSpecific3
     ...

So, for your users in the room can read the message simply:

FirebaseRef.child ("rooms/charOfYourRoomSpecific/messages");

And everyone who has access to this room will see in real time their conversations.