這篇我們來實作firebase部分,先簡單看張圖來理解如何實現雙人連線的架構:
在一回合內,會發生4個動作:
我們利用雙方玩家的設備端上傳(uploadData),以及更新UI(getData)的過程,達成模擬雙人連線的效果
所以,設備端會需要實作新增(add)、取得(get)、上傳(upload)、刪除(delete)四種功能,本專案使用MVP架構中Contract及Presenter部分處理回調的資料
private FirebaseFirestore database = FirebaseFirestore.getInstance();
private DatabaseContract.view callback;
public DatabasePresenter(DatabaseContract.view view) {
this.callback = view;
}
@Override
public void addData(String roomNumber,
Boolean player1OnlineState,
Boolean player2OnlineState,
String moveState,
HashMap<String,Object> chessboardData,
HashMap<String,Object> chessmanMoveData,
String turn,
HashMap<String,Object> pawnMove1,
HashMap<String,Object> pawnMove2,
HashMap<String,Object> castlingMove1,
HashMap<String,Object> castlingMove2,
String date,
String player1message,
String player2message,
String winPlayer){
HashMap<String,Object> RoomData = new HashMap<>();
RoomData.put("RoomNumber", roomNumber);
RoomData.put("Player1OnlineState", player1OnlineState);
RoomData.put("Player2OnlineState", player2OnlineState);
RoomData.put("MoveState", moveState);
RoomData.put("ChessboardData", chessboardData);
RoomData.put("ChessmanMoveData", chessmanMoveData);
RoomData.put("Turn", turn);
RoomData.put("PawnMove1", pawnMove1);
RoomData.put("PawnMove2", pawnMove2);
RoomData.put("CastlingMove1", castlingMove1);
RoomData.put("CastlingMove2", castlingMove2);
RoomData.put("Date", date);
RoomData.put("Player1message", player1message);
RoomData.put("Player2message", player2message);
RoomData.put("WinPlayer", winPlayer);
new Thread(() -> {
database.collection("RoomData")
.add(RoomData)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
callback.addSuccess();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.addError();
}
});
}).start();
}
當中各參數意義:
下一篇我們再介紹get方法