在变量达到预定义值后运行函数

时间:2018-06-18 18:51:18

标签: javascript

我有一个全局变量

var trigger = 0;

另外我有一些功能,一旦完成,它们就会增加这个变量的值。

我的目标是在变量触发器达到值2后触发附加功能。

实现这一目标的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

一种可能的选择就是在触发器上放置间隔监视器。

WaitAll()

答案 1 :(得分:0)

这是否可以让您深入了解如何实现增加触发器的函数?



    @SuppressLint("ResourceType")
private void addInvitaionPlayerUi(String pname) {
    LinearLayout layout = findViewById(R.id.linearLay_invitations);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

    //set new View
    TextView view = new TextView(this);
    view.setLayoutParams(params);
    view.setTextSize(18);
    view.setTextColor(ContextCompat.getColor(this,R.color.colorPrimaryFont));
    view.setPadding(50,50,50,50);
    view.setBackgroundResource(R.layout.button_style5);
    view.setText(pname+"      waiting");

    layout.addView(view);
}

@SuppressLint("ResourceType")
private void addInvitaionPlayerUi(final Invitation invitation) {
    LinearLayout layout = findViewById(R.id.linearLay_invitations);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

    //set new view
    TextView view = new TextView(this);
    view.setLayoutParams(params);
    view.setTextSize(18);
    view.setTextColor(ContextCompat.getColor(this,R.color.colorPrimaryFont));
    view.setPadding(50,50,50,50);
    view.setBackgroundResource(R.layout.button_style5);

    view.setText(invitation.getInviter().getDisplayName()+"      clickToAccept");
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(SystemClock.elapsedRealtime() - lastClickTime < 600)
                return;
            lastClickTime = SystemClock.elapsedRealtime();
            turnBasedMultiplayerClient.acceptInvitation(invitation.getInvitationId());
            System.out.println("Enemys Invitation accepted");
            turnBasedMultiplayerClient.loadMatch(invitation.getInvitationId()).addOnSuccessListener(new OnSuccessListener<AnnotatedData<TurnBasedMatch>>() {
                @Override
                public void onSuccess(AnnotatedData<TurnBasedMatch> turnBasedMatchAnnotatedData) {
                    startARound(turnBasedMatchAnnotatedData.get().getMatchId());
                }
            });
        }
    });

    layout.addView(view);
}

private void addAllInvitationsToUi(InvitationBuffer pinvitationBuffer) {
    for (int i = 0; i < pinvitationBuffer.getCount(); i++) {
        Invitation invitation = pinvitationBuffer.get(i);
        if(invitation.getInviter().getPlayer().getPlayerId() == playersId) { //eine von meinen gesendeten Einladungen
            String name;
            if(invitation.getParticipants().get(0).getPlayer().getPlayerId() == playersId)
                name = invitation.getParticipants().get(1).getDisplayName();
            else
                name = invitation.getParticipants().get(0).getDisplayName();
            addInvitaionPlayerUi(name);
        } else { //eine bekommene einladung
            addInvitaionPlayerUi(invitation);
        }
    }
}

@SuppressLint("ResourceType")
private void addActiveGamePlayerUiMyTurn(String opponent, final String pmatchId) {
    LinearLayout layout = findViewById(R.id.linearLay_active);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

    //set new view
    TextView view = new TextView(this);
    view.setLayoutParams(params);
    view.setTextSize(18);
    view.setTextColor(ContextCompat.getColor(this,R.color.colorPrimaryFont));
    view.setPadding(50,50,50,50);
    view.setBackgroundResource(R.layout.button_style5);

    view.setText(opponent+"      clickToPlay");
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(SystemClock.elapsedRealtime() - lastClickTime < 600)
                return;
            lastClickTime = SystemClock.elapsedRealtime();
            System.out.println("Clicked play game");
            startARound(pmatchId);
        }
    });

    layout.addView(view);
}

@SuppressLint("ResourceType")
private void addActiveGamePlayerUiTheriTurn(String opponent) {
    LinearLayout layout = findViewById(R.id.linearLay_active);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

    //set new view
    TextView view = new TextView(this);
    view.setLayoutParams(params);
    view.setTextSize(18);
    view.setTextColor(ContextCompat.getColor(this,R.color.colorPrimaryFont));
    view.setPadding(50,50,50,50);
    view.setBackgroundResource(R.layout.button_style5);

    view.setText(opponent+"      waiting to play");

    layout.addView(view);
}

private void addAllActiveGamesToUi(LoadMatchesResponse ploadMatchesResponse) {
    //Add my turn games
    for (int i = 0; i < ploadMatchesResponse.getMyTurnMatches().getCount(); i++) {
        String name;
        if(ploadMatchesResponse.getMyTurnMatches().get(i).getParticipantIds().get(0) == playersId)
            name = ploadMatchesResponse.getMyTurnMatches().get(i).getParticipantIds().get(1);
        else
            name = ploadMatchesResponse.getMyTurnMatches().get(i).getParticipantIds().get(0);
        addActiveGamePlayerUiMyTurn(name,ploadMatchesResponse.getMyTurnMatches().get(i).getMatchId());
    }
    //Add their turn games
    for (int i = 0; i < ploadMatchesResponse.getTheirTurnMatches().getCount(); i++) {
        String name;
        if(ploadMatchesResponse.getTheirTurnMatches().get(i).getParticipantIds().get(0) == playersId)
            name = ploadMatchesResponse.getTheirTurnMatches().get(i).getParticipantIds().get(1);
        else
            name = ploadMatchesResponse.getTheirTurnMatches().get(i).getParticipantIds().get(0);
        addActiveGamePlayerUiTheriTurn(name);
    }
}

private void openMenuActivity() {
    Intent intent = new Intent(this,MenuACT.class);
    startActivity(intent);
}

public void onBackPressed(){
    openMenuActivity();
}

////////////GOOOOGLE///////////////////
private void signInToGoogle() {
    //Google Play Service
    mGoogleClient = GoogleSignIn.getClient(this,
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build());
    signInSilently();
}

private void signInSilently() { //wennman sich schon einaml angemaldet hat...
    System.out.println("signInSilently()");

    mGoogleClient.silentSignIn().addOnCompleteListener(this,
            new OnCompleteListener<GoogleSignInAccount>() {
                @Override
                public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                    if (task.isSuccessful()) {
                        System.out.println("signInSilently(): success");
                        onConnected(task.getResult());
                    } else {
                        System.out.println("signInSilently(): failure "+task.getException());
                        onDisconnected();
                    }
                }
            });
}

private void onConnected(GoogleSignInAccount googleSignInAccount) {
    System.out.println("connected to Google APIs...");

    //Add data to client variables
    playersClient = Games.getPlayersClient(this,googleSignInAccount);
    invitationsClient = Games.getInvitationsClient(this,googleSignInAccount);
    turnBasedMultiplayerClient = Games.getTurnBasedMultiplayerClient(this,googleSignInAccount);

    //Get all active matches (my turn and theire turn)
    turnBasedMultiplayerClient.loadMatchesByStatus(Multiplayer.SORT_ORDER_MOST_RECENT_FIRST,new int[]{TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN,TurnBasedMatch.MATCH_TURN_STATUS_THEIR_TURN}).addOnSuccessListener(new OnSuccessListener<AnnotatedData<LoadMatchesResponse>>() {
        @Override
        public void onSuccess(AnnotatedData<LoadMatchesResponse> loadMatchesResponseAnnotatedData) {
            addAllActiveGamesToUi(loadMatchesResponseAnnotatedData.get());
        }
    });

    //Load and save current players Id
    playersClient.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
        @Override
        public void onSuccess(Player player) {
            playersId = player.getPlayerId();
        }
    });
    // As a demonstration, we are registering this activity as a handler for
    // invitation and match events.

    // This is *NOT* required; if you do not register a handler for
    // invitation events, you will get standard notifications instead.
    // Standard notifications may be preferable behavior in many cases.
    invitationsClient.registerInvitationCallback(mInvitationCallback);
    invitationsClient.loadInvitations().addOnSuccessListener(new OnSuccessListener<AnnotatedData<InvitationBuffer>>() {
        @Override
        public void onSuccess(AnnotatedData<InvitationBuffer> invitationBufferAnnotatedData) {
            addAllInvitationsToUi(invitationBufferAnnotatedData.get());
        }
    });

    // Likewise, we are registering the optional MatchUpdateListener, which
    // will replace notifications you would get otherwise. You do *NOT* have
    // to register a MatchUpdateListener.
    turnBasedMultiplayerClient.registerTurnBasedMatchUpdateCallback(mMatchUpdateCallback);

    //Add Popup Messages
    Games.getGamesClient(this,googleSignInAccount).setGravityForPopups(Gravity.TOP);
    Games.getGamesClient(this,googleSignInAccount).setViewForPopups(this.getWindow().getDecorView());
}

private void onDisconnected() {
    System.out.println("disconnected...");
}

//Called when receiving Invitation
private InvitationCallback mInvitationCallback = new InvitationCallback() {
    // Handle notification events.
    @Override
    public void onInvitationReceived(@NonNull Invitation invitation) {
        Toast.makeText(MultiplayerMenuACT.this,"An invitation has arrived from " + invitation.getInviter().getDisplayName(), Toast.LENGTH_SHORT).show();
        addInvitaionPlayerUi(invitation);
    }

    @Override
    public void onInvitationRemoved(@NonNull String invitationId) {
        Toast.makeText(MultiplayerMenuACT.this, "An invitation was removed.", Toast.LENGTH_SHORT).show();
    }
};

//Called when Match been updated
private TurnBasedMatchUpdateCallback mMatchUpdateCallback = new TurnBasedMatchUpdateCallback() {
    @Override
    public void onTurnBasedMatchReceived(@NonNull TurnBasedMatch turnBasedMatch) {
        Toast.makeText(MultiplayerMenuACT.this, "A match was updated.", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onTurnBasedMatchRemoved(@NonNull String matchId) {
        Toast.makeText(MultiplayerMenuACT.this, "A match was removed.", Toast.LENGTH_SHORT).show();
    }
};

//--- 3er pair Multiplayer ---//

private void openMultiplayerNewGameAfterSilent() {
    mGoogleClient.silentSignIn().addOnCompleteListener(this, new OnCompleteListener<GoogleSignInAccount>() {
        @Override
        public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
            if (task.isSuccessful()) {
                System.out.println("signInSilently(): success");
                onConnectedForShowingMultiplayer(task.getResult());
            } else {
                System.out.println("signInSilently(): failure "+task.getException());
                onDisconnected();
            }
        }
    });
}

private void onConnectedForShowingMultiplayer(GoogleSignInAccount googleSignInAccount) {
    System.out.println("connected to Google APIs...");
    turnBasedMultiplayerClient = Games.getTurnBasedMultiplayerClient(this, googleSignInAccount);
    showMutiplayerUnsafe();
}

private void showMutiplayerUnsafe() {
    turnBasedMultiplayerClient.getSelectOpponentsIntent(1,1,false) //einen genger suchen/automacth allowed
            .addOnSuccessListener(new OnSuccessListener<Intent>() {
                @Override
                public void onSuccess(Intent intent) {
                    startActivityForResult(intent, RC_SELECT_PLAYERS);
                }
            });
}

//When a google intent Activity has been closed
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SELECT_PLAYERS) { //user select players and a new game can start
        if (resultCode != Activity.RESULT_OK) {
            // Canceled or other unrecoverable error.
            return;
        }
        ArrayList<String> invitees = data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);

        // Get automatch criteria
        Bundle autoMatchCriteria = null;
        int minAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
        int maxAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);

        TurnBasedMatchConfig.Builder builder = TurnBasedMatchConfig.builder()
                .addInvitedPlayers(invitees);
        if (minAutoPlayers > 0) {
            builder.setAutoMatchCriteria(
                    RoomConfig.createAutoMatchCriteria(minAutoPlayers, maxAutoPlayers, 0));
        }
        Games.getTurnBasedMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
                .createMatch(builder.build()).addOnCompleteListener(new OnCompleteListener<TurnBasedMatch>() {
            @Override
            public void onComplete(@NonNull Task<TurnBasedMatch> task) {
                if (task.isSuccessful()) {
                    TurnBasedMatch match = task.getResult();
                    if (match.getData() == null) {
                        // First turn, initialize the game data.
                        // (You need to implement this).
                        initializeGameData(match);
                        addInvitaionPlayerUi(match.getParticipantIds().get(0));
                    }
                } else {
                    // There was an error. Show the error.
                    int status = CommonStatusCodes.DEVELOPER_ERROR;
                    Exception exception = task.getException();
                    if (exception instanceof ApiException) {
                        ApiException apiException = (ApiException) exception;
                        status = apiException.getStatusCode();
                    }
                    //handleError(status, exception);
                    System.out.println("Error making match: "+exception);
                }
            }
        });
    }
}

private void initializeGameData(TurnBasedMatch match) {
    System.out.println("Initialising Game Data...");
    try {
        //Ersten Match Storage anmachen
        MatchStorage ms;
        ms = new MatchStorage();
        ms.round = 1;
        ms.thisActiveExcercisesPlayedBy = 0;
        ms = SerializationUtils.deserialize(match.getData());

        String opponentId;
        if(match.getParticipantIds().get(0) == playersId)
            opponentId = match.getParticipantIds().get(1);
        else
            opponentId = match.getParticipantIds().get(0);
        //Spieldaten initalisieren
        turnBasedMultiplayerClient.takeTurn(match.getMatchId(), SerializationUtils.serialize(ms),opponentId).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                System.out.println("Failed udpating game data "+e);
            }
        });
    } catch (Exception e) {
        System.out.println("Error updating TurnBasedMultiplayer: "+e);
    }
}

private void startARound(String matchId) {
    Intent intent = new Intent(this,MultiplayerACT.class);
    intent.putExtra("matchId",matchId);
    startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
}

@Override
protected void onResume() {
    super.onResume();
    signInSilently();
}
&#13;
&#13;
&#13;