我为我的应用程序提供了一个简单的多人游戏,而且游戏玩法非常简单。每个玩家都必须按“准备”,然后游戏才能开始。
两个玩家都准备好之后,将gameStarted设置为true,并且应该进行游戏(完全不受玩家控制)。这行得通,但是问题是它在一个循环中发生了不止一次。这是我拥有的值事件侦听器。
games.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
HomePage.getCurrentGameID(new HomePage.CallbackID() {
@Override
public void onSuccess(String currentGameID) {
if (dataSnapshot.child(currentGameID).child("player1").child("ready").getValue().equals(true)
&& dataSnapshot.child(currentGameID).child("player2").child("ready").getValue().equals(true)) {
counter.run();
}
if (dataSnapshot.child(currentGameID).child("gameStarted").getValue().equals(true) &&
dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(1)) {
headsOrTails.setText("Heads");
Log.i("FlipCoin", ";;happened");
flipHeads();
getResults();
endGame();
} else if (dataSnapshot.child(currentGameID).child("gameStarted").getValue().equals(true) &&
dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(2)) {
headsOrTails.setText("Tails");
Log.i("FlipCoin", ";;happened");
flipTails();
getResults();
endGame();
}
这是我的getResults()方法。我将其放在此处以表明我从上面显示的addListenerForSingleValueEvent
中调用了另一个值事件侦听器
private void getResults() {
games.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
HomePage.getCurrentGameID(new HomePage.CallbackID() {
@Override
public void onSuccess(final String currentGameID) {
final String horT1 = dataSnapshot.child(currentGameID).child("player1").child("horT").getValue().toString();
final String horT2 = dataSnapshot.child(currentGameID).child("player2").child("horT").getValue().toString();
final double wager = Double.parseDouble(dataSnapshot.child(currentGameID).child("wager").getValue().toString());
HomePage.getUserPosition(new HomePage.CallbackPosition() {
@Override
public void onSuccess(int position) {
if(position == 1) {
if(horT1.equals("Heads") && dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(1)
|| horT1.equals("Tails") && dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(2)) {
getWinner(FirebaseAuth.getInstance().getUid(), wager);
} else {
getLoser(FirebaseAuth.getInstance().getUid(), wager);
}
}
if(position == 2) {
if(horT2.equals("Heads") && dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(1)
|| horT2.equals("Tails") && dataSnapshot.child(currentGameID).child("horT").getValue(Integer.class).equals(2)) {
getWinner(FirebaseAuth.getInstance().getUid(), wager);
} else {
getLoser(FirebaseAuth.getInstance().getUid(), wager);
}
}
if(dataSnapshot.child(currentGameID).child("gameFinished").getValue().equals(true)) {
//games.child(currentGameID).removeValue();
}
endGame();
}
});
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
});
我认为将其设置为单一值事件侦听器只会使其发生一次,但是我有一个登录信息,当我运行游戏时会被循环调用。
如何使此事件发生一次?