Avoid conflicting when "matching" users for multiplayer game - ios

I have tried both FireBase and PubNub to create this simple multiplayer game. Created with only two players. One big(and justified) concern is conflicting users. Let me explain :
each "game" constructed with just two players(not more). If 4 players logs as the same time. And each player search for a "match". player one might match with player two.while player two might match with player three, and so on.
How can i avoid it, and guarantee that each player will get a single and unique match?, or in other words , prevent matching one user with more than other one

With Firebase, security rules and transactions would be the key to an elegant solution.
If you're willing to set up a node.js script or other server-side worker, this is fairly straightforward. Players would write to a "lobby" when they want a match. The server script would perform the matches and write back the "game room" they are going to join. The structure would be basically thus:
/games/$game_id/users/user1/<user_id>
/games/$game_id/users/user2/<user_id>
/lobby/$user_id/false (an unmatched user)
/lobby/$user_id/$game_id (a matched user)
Now clients would simply write to the lobby when they want to join a game, and then wait for the server to assign them a game id:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
var lobbyRef = ref.child('lobby/' + <my user id>);
lobbyRef.set(false); // I want to join a game
lobbyRef.on('value', function(snap) {
if( snap.val() !== null ) {
console.log('I joined a game!', snap.val());
}
});
The server is nearly as simple. Assuming node.js:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
var lobbyRef = ref.child('lobby');
var gamesRef = ref.child('games');
var player1 = null;
// listen for requests to join
lobbyRef.on('child_added', function(snap) {
// assign as player1 if nobody is waiting
if( !player1 ) {
player1 = snap.ref();
}
// if someone is already waiting, assign both players a room
else {
var player2 = snap.ref();
var gameRef = gamesRef.push({
players: {
player1: player1.key(),
player2: snap.key()
}
}, function(err) {
if( err ) { throw err; } // a bug
// let the players know they have been matched and which room to join
player1.set(gameRef.key());
player2.set(gameRef.key());
});
}
});
Obviously there is some work to make all this fault tolerant and security rules would be needed to prevent cheating.
Doing this entirely on the client is slightly more involved, but certainly manageable.
Have each player attempt to match themselves to anybody in the lobby. If nobody is in the lobby, then wait there. This is done with a transaction to prevent conflicts.
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
var lobbyRef = ref.child('lobby');
function waitInLobby() {
lobbyRef.once('value', lobbyUpdated);
}
function lobbyUpdated(snap) {
if( snap.val() === null ) {
// lobby is empty, so join and wait
var ref = lobbyRef.child('<my user id>').push(false);
ref.on('value', someoneMatchedMe);
function someoneMatchedMe(snap) {
if( snap.val() !== false ) {
console.log('I got matched in room', snap.val());
ref.off('value', someoneMatchedMe); // stop monitoring
snap.ref().remove(); // leave the lobby
}
}
}
else {
// lobby is not empty, so try to match someone
var possibles = [];
snap.forEach(function(ss) {
possibles.push(ss.ref());
});
}
}
function matchUser(possibles) {
if( !possibles.length ) { waitInLobby(); }
var opponentRef = lobbyRef.child(possibles.shift());
opponentRef.transaction(function(currentVal) {
if( currentVal !== false ) {
// already claimed, start over
matchUser(possibles);
}
});
}
Some security rules would be critical here, in addition to the transactions. There is also plenty of room for optimization, but at the point that you're optimizing for production, that's a job for your engineering team, rather than a Stack Overflow contributor.

matching
[p1] - [p2] - [p3] - [p4] - [p5] - etc...
Ok so you match odd numbered player (N) with the next even numbered player (N + 1).
Of course P5 stays alone and should wait for the next round, make him P1 for that round. That way he never has to wait 2 rounds
You can create a tuple for the pairs, but I would make the Player class also have a field oponent of type Player
edit1: You keep track of the raw queue in a regular array of Players. As soon as the array reaches it's desired size you trigger the above algorithm which stops the ability to change to current player pool and all matches will be definitive.
idle check
Ok so you let players enter the queue and you display a timer / empty slot counter so they have feedback how long they have to wait.
As soon as the match starts you let them lock in (League of Legends does it this way as well)
If 1 or more players do not lock in you start the queue process over, maybe with a decreased timer so the players don't have to wait to long.
If you make this time based (not slot based) then if 1 players does not respond (let's say P2) you move the last player (P5) to his slot (P5 is now P2) and everyone can play.
If you have more questions I will edit this answer.

Related

Nested Cursors over two different Stores

I have following code:
...
Transaction xodusTransaction = xodusEnvironment.beginReadonlyTransaction();
Store leftStore = xodusEnvironment.openStore(leftName, StoreConfig.USE_EXISTING, xodusTransaction, false);
Store rightStore = xodusEnvironment.openStore(rightName, StoreConfig.USE_EXISTING, xodusTransaction, false);
try(Cursor leftCursor = leftStore.openCursor(xodusTransaction);
Cursor rightCursor = rightStore.openCursor(xodusTransaction)) {
while(leftCursor.getNext()) {
while(rightCursor.getNext()) {
// Do actual work with data from both stores
}
}
}
...
I expect that internal loop will be fired N*M times, where N - cardinality of leftStore and M - cardinality of rightStore.
On practice external loop fires only once and internal loop fires M-times.
If I rewrite the code in following way (flattering nested loops):
...
while(leftCursor.getNext()) {
...
}
while(rightCursor.getNext()) {
...
}
...
Then both loops fires as expected N-times for leftStore and M-times for rightStore.
The question is: is it possible to make nested cursor traveling? If yes, kindly please guide me.
Thank you!
-Taras
Once cursor.getNext() returned false (there is no next key/value pair), it will never return true for this Cursor instance. To traverse a Store again, reopen cursor.
Here is the code traversing two Stores as a matrix, i.e. all pairwise combinations of key/value pairs from both Stores:
try (Cursor leftCursor = leftStore.openCursor(txn)) {
while (leftCursor.getNext()) {
try (Cursor rightCursor = rightStore.openCursor(txn)) {
while (rightCursor.getNext()) {
// Do actual work with data from both stores
}
}
}
}

Coding a type of random walk in Neo4j using the Traversal Framework

I'm currently working on a graph where nodes are connected via probabilistic edges. The weight on each edge defines the probability of existence of the edge.
Here is an example graph to get you started
(A)-[0.5]->(B)
(A)-[0.5]->(C)
(B)-[0.5]->(C)
(B)-[0.3]->(D)
(C)-[1.0]->(E)
(C)-[0.3]->(D)
(E)-[0.3]->(D)
I would like to use the Neo4j Traversal Framework to traverse this graph starting from (A) and return the number of nodes that have been reached based on the probability of the edges found along the way.
Important:
Each node that is reached can only be counted once. -> If (A) reaches (B) and (C), then (C) need not reach (B). On the other hand if (A) fails to reach (B) but reaches (C) then (C) will attempt to reach (B).
The same goes if (B) reaches (C), (C) will not try and reach (B) again.
This is a discrete time step function, a node will only attempt to reach a neighboring node once.
To test the existence of an edge (whether we traverse it) we can generate a random number and verify if it's smaller than the edge weight.
I have already coded part of the traversal description as follows. (Here it is possible to start from multiple nodes but that is not necessary to solve the problem.)
TraversalDescription traversal = db.traversalDescription()
.breadthFirst()
.relationships( Rels.INFLUENCES, Direction.OUTGOING )
.uniqueness( Uniqueness.NODE_PATH )
.uniqueness( Uniqueness.RELATIONSHIP_GLOBAL )
.evaluator(new Evaluator() {
#Override
public Evaluation evaluate(Path path) {
// Get current
Node curNode = path.endNode();
// If current node is the start node, it doesn't have previous relationship,
// Just add it to result and keep traversing
if (startNodes.contains(curNode)) {
return Evaluation.INCLUDE_AND_CONTINUE;
}
// Otherwise...
else {
// Get current relationhsip
Relationship curRel = path.lastRelationship();
// Instantiate random number generator
Random rnd = new Random();
// Get a random number (between 0 and 1)
double rndNum = rnd.nextDouble();
// relationship wc is greater than the random number
if (rndNum < (double)curRel.getProperty("wc")) {
String info = "";
if (curRel != null) {
Node prevNode = curRel.getOtherNode(curNode);
info += "(" + prevNode.getProperty("name") + ")-[" + curRel.getProperty("wc") + "]->";
}
info += "(" + curNode.getProperty("name") + ")";
info += " :" + rndNum;
System.out.println(info);
// Keep node and keep traversing
return Evaluation.INCLUDE_AND_CONTINUE;
} else {
// Don't save node in result and stop traversing
return Evaluation.EXCLUDE_AND_PRUNE;
}
}
}
});
I keep track of the number of nodes reached like so:
long score = 0;
for (Node currentNode : traversal.traverse( nodeList ).nodes())
{
System.out.print(" <" + currentNode.getProperty("name") + "> ");
score += 1;
}
The problem with this code is that although NODE_PATH is defined there may be cycles which I don't want.
Therefore, I would like to know:
Is there is a solution to avoid cycles and count exactly the number of nodes reached?
And ideally, is it possible (or better) to do the same thing using PathExpander, and if yes how can I go about coding that?
Thanks
This certainly isn't the best answer.
Instead of iterating on nodes() I iterate on the paths, and add the endNode() to a set and then simply get the size of the set as the number of unique nodes.
HashSet<String> nodes = new HashSet<>();
for (Path path : traversal.traverse(nodeList))
{
Node currNode = path.endNode();
String val = String.valueOf(currNode.getProperty("name"));
nodes.add(val);
System.out.println(path);
System.out.println("");
}
score = nodes.size();
Hopefully someone can suggest a more optimal solution.
I'm still surprised though that NODE_PATH didn't not prevent cycles from forming.

GKTurnBasedMatch doesn't consistently advance to the next player (Xamarin, Apple GameKit)

I'm using a turn-based match for a board game, and when a turn is complete I call GKTurnBasedMatch.EndTurn and pass the match participants and the new match data as the arguments. I need the game to advance to the unmatched players, but it only does so after some indeterminate time related to the timeout value. Setting the timeout value 0 only prevents the game from ever progressing past player 1. The match data is being updated, so the app is definitely communicating with Game Center servers. What am I missing here?
private void endTurn(double timeout)
{
// Copies list of participants to a mutable array
GKTurnBasedParticipant[] Participants = new GKTurnBasedParticipant[match.Participants.Length];
match.Participants.CopyTo(Participants, 0);
// Advances to the next player
match.EndTurn(Participants, timeout, matchData, (e) =>
{
// If there is an error message, print it to the console
if (e != null)
{
Console.WriteLine(e.LocalizedDescription);
Console.WriteLine(e.LocalizedFailureReason);
}
// Otherwise proceed normally
else
turnOverUpdate();
});
}
Apple's documentation is quite poor for the EndTurn method, but I figured it out. The NextParticipants field should be treated like EndTurnWithNextParticipant, so you have to copy GKTurnBasedMatch.Participants and reorder it so the next player is first and so fourth. The match only gives you the participants in order of joining, not relative to the local player, so you have to sort it. Below is the code I used to accomplish this.
List<GKTurnBasedParticipant> participants = new List<GKTurnBasedParticipant>();
// Gets the index of the local player
int index = 0;
for (int i = 0; i < match.Participants.Length; i++)
{
if (match.Participants[i].Player != null)
{
if (match.Participants[i].Player.PlayerID == GKLocalPlayer.LocalPlayer.PlayerID)
{
index = i;
break;
}
}
}
int offset = match.Participants.Length - index;
for (int i = 1; i < offset; i++)
participants.Add(match.Participants[i + index]);
for (int i = 0; i <= index; i++)
participants.Add(match.Participants[i]);
GKTurnBasedParticipant[] nextParticipants = participants.ToArray();

Run Tarantool Lua function in another coroutine

I use NoSQL database Tarantool and try to do some complex work on DB side using Lua stored procedures. I think it`s a good idea, because i can do less DB calling and have less overhead with network data transfer.
I have some table:
user_counters: id, counter_a, counter_b, score
And, for example, i have some function to calculate field score:
function recalc_score(id)
local stream = box.space.user_counters:select { id }
local rating = 0
-- some_rating_calculation using counter_a and counter_b here
box.space.user_counters:update(id, { { '=', 4, rating } })
end
And i have another function for fields counter_a and counter_b update:
function update_user_counters(id, counter_a_diff, counter_b_diff)
local rating_default = 0
local user_counters_tuple = box.space.user_counters:upsert(
{ id, counter_a_diff, counter_b_diff, rating_default },
{ { '+', 2, counter_a_diff }, { '+', 3, counter_b_diff } }
)
-- start another coroutine recalc_score(id) and forget about it
return user_counters_tuple
end
How can i call recalc_score(id) function and return user_counters_tuple without waiting when previous function execution will be finished?
Just use fiber.create(fun, ...):
local fiber = require('fiber')
-- start another coroutine recalc_score(id) and forget about it
fiber.create(recalc_score, id)

removeAtIndex() not working on Swift array

I have a Swift n00b question.
I'm having a hard time understanding why I cannot remove an element from an array.
I first filter it twice to contain only the values I need:
let filteredShowtimes = movieShowtimes.filter{$0.dateTime.laterDate(newStartTime!).isEqualToDate($0.dateTime)}
var furtherFilteredShowtimes = filteredShowtimes.filter{$0.endTime.earlierDate(endTime!).isEqualToDate($0.endTime)}
And, down the line, inside a while loop that depends on the size of the array - but doesn't iterate over it or modify it - I try removing the first element like so:
furtherFilteredShowtimes.removeAtIndex(0)
But the element count remains the same.
Any idea what I'm missing?
Here's the whole code:
while(furtherFilteredShowtimes.count > 0) {
println("showtime \(furtherFilteredShowtimes.first!.dateTime)")
//if the start time of the movie is after the start of the time period, and its end before
//the requested end time
if (newStartTime!.compare(furtherFilteredShowtimes.first!.dateTime) == NSComparisonResult.OrderedAscending) && (endTime!.compare(furtherFilteredShowtimes.first!.endTime) == NSComparisonResult.OrderedDescending) {
let interval = 1200 as NSTimeInterval
//if the matching screenings dict already contains one movie,
//make sure the next one starts within 20 min of the previous
//one
if(theaterMovies.count > 1 && endTime!.timeIntervalSinceDate(newStartTime!) < interval {
//add movie to the matching screenings dictionary
println("we have a match with \(movies[currentMovie.row].title)")
theaterMovies[furtherFilteredShowtimes.first!.dateTime] = movies[currentMovie.row].title
//set the new start time for after the added movie ends
newStartTime = movieShowtimes.first!.endTime
//stop looking for screenings for this movie
break
}
else if(theaterMovies.count == 0) {
//add movie to the matching screenings dictionary
theaterMovies[furtherFilteredShowtimes.first!.dateTime] = movies[currentMovie.row].title
println("we have a new itinerary with \(movies[currentMovie.row].title)")
//set the new start time for after the added movie ends
newStartTime = furtherFilteredShowtimes.first!.endTime
//stop looking for screenings for this movie
break
}
}
else { //if the showtime doesn't fit, remove it from the list
println("removing showtime \(furtherFilteredShowtimes.first!.dateTime)")
furtherFilteredShowtimes.removeAtIndex(0)
}
}
You only say removeAtIndex(0) in one place, in an else.
So if it doesn't happen, that means that line is never being executed because the else is not executed - the if is executed instead.
And you break at the end of each if, so that's the end of the while loop!
In other words, let's pretend that the first two nested if conditions succeed. Your structure is like this:
while(furtherFilteredShowtimes.count > 0) {
if (something) {
if (somethingelse) {
break
break means jump out of the while, so if those two if conditions succeed, that's the end! We never loop. We certainly will never get to the removeAtIndex().

Resources