Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class FirebasePlayerMatchMaker {
public static interface OnMatchMadeCallback {
public void run(FirebasePlayerMatchMaker c);
}
public static final String RANDOM_ROOM_ID = "/Globl";
public static final String ROOM_ID = "/GameRooms";
public static final String GAMES_RECORD = "/OpenGameMoves";
private DatabaseReference mUserRoomRef;
private DatabaseReference mOwnChallengeRef;
public String mOpener;
public String mGamePath;
public int mLocalPlayerIndex;
private boolean mClosed = false;
private OnMatchMadeCallback mOnComplete;
public boolean isClosed() {
return mClosed;
}
private FirebasePlayerMatchMaker(DatabaseReference userRoomRef, OnMatchMadeCallback onComplete) {
mUserRoomRef = userRoomRef;
mOnComplete = onComplete;
}
protected Matcher mMatcher;
protected SelfChallengeManager mSelfChallengeManager;
protected SelfChallengeCanceller mSelfChallengeCanceller;
public void findMatch() {
new Thread(new Runnable() {
@Override
public void run() {
OnFailCallback onMatchNotFoundFallback = new OnFailCallback() {
@Override
public void onFail() {
mMatcher = null;
mSelfChallengeManager = new SelfChallengeManager();
mUserRoomRef.runTransaction(mSelfChallengeManager);
}
};
mMatcher = new Matcher(onMatchNotFoundFallback);
mUserRoomRef.runTransaction(mMatcher);
}
}).start();
}
public void stop() {
if (mSelfChallengeManager == null ||
mSelfChallengeCanceller != null) {
return;
}
mSelfChallengeCanceller = new SelfChallengeCanceller(mSelfChallengeManager);
mUserRoomRef.runTransaction(mSelfChallengeCanceller);
}
public static FirebasePlayerMatchMaker newInstance(String userRoom, OnMatchMadeCallback onComplete) {
return new FirebasePlayerMatchMaker(
FirebaseDatabase.getInstance().getReference(ROOM_ID + "/" + userRoom), onComplete);
}
private boolean isChallengeCompat(Challenge oppoChallenge) {
return true;
}
protected boolean mIsThisOpener;
protected void onMatchFound(boolean isOpener) {
mIsThisOpener = isOpener;
mLocalPlayerIndex = (isOpener) ? 1 : 0;
mOnComplete.run(this);
}
public boolean isThisOpener() {
return mIsThisOpener;
}
public interface OnFailCallback {
public void onFail();
}
protected class Matcher implements Transaction.Handler;
protected class SelfChallengeManager implements Transaction.Handler, ValueEventListener;
protected class SelfChallengeCanceller implements Transaction.Handler;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment