1
\$\begingroup\$

I'm making a turn based game in java for fun, it follows a set game flow pattern contained in a loop. I realized that once a player hits a win condition the game continues playing out the rest of the turn, possibly changing the victor.

Do I need to go back and put if statements everywhere so nothing is executed once a victor is declared? Is there a more elegant solution?

\$\endgroup\$
1
  • \$\begingroup\$ Typically you either end the game upon victory or defeat OR allow player to continue playing just for fun. Either way - it's your choice first. \$\endgroup\$
    – Kromster
    Jul 28, 2018 at 17:34

2 Answers 2

1
\$\begingroup\$

Instead of doing that, just make sure to not allow the game to change the victor. If your language has getters and setters, then inside the victor's setter check if it already has been defined. Only change it, if it wasn't. If it doesn't support native setters, then simply create a setter method with the same goal and make the variable private.

\$\endgroup\$
2
  • \$\begingroup\$ i do think it is a very bad idea to put logic into a setter! instead break the loop once you know who has won. \$\endgroup\$ Aug 2, 2018 at 11:12
  • \$\begingroup\$ @MartinFrank I don't think a simple "if (var != null) var = value" would slow anything down by a considerable amount, especially since you only use this a couple of times \$\endgroup\$
    – Bálint
    Aug 2, 2018 at 18:41
0
\$\begingroup\$

you should break the loop when the condition is reached. most programming languages provide mechanismens to break a loop.

example language:

do{
    player.performAction();
    boolean playerHasWon = checkPlayerWinCondidtion();
    if( playerHasWon){
        //maybe perform other actions here, ut later and ultimatly...break
        break; //breaks the loop here
    }
    opponent.performAction();
    boolean opponentHasWon = checkOpponentWinCondition();
    if(opponentHasWon){
        break; //breaks the loop here
    }
while(true);

not that you need an endless loop, just as an example...

anyway for your question: yes, you answered that thign already correct. you have to use if statements, that would be the proper way to do it... there are fancy ways of programming such stuff but in the end it is the right way to do it.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .