Search code examples
pythonlogicboolean-logic

How to break while loop immediately after condition is met (and not run rest of code)?


I have this dice game made in python for class, I am using functions for the scoring logic (which I believe is all working as desired). I have put these functions in a while loop so that when either player reaches 100 banked score the game ends. However, I cannot get this to work as intended.

while int(player1Score) < 100 or int(player2Score) < 100:
    player1()
    player2()

Here is one of the functions (the other is the same with score added to player 2's variable and some output changes):

def player1():
    global player1Score #global score to reference outside of function
    rTotal = 0 #running total - used when gamble
    
    print("\nPlayer 1 turn!")
    while 1==1:   
        d = diceThrow() #dicethrow output(s)
        diceIndexer(d)
        print(f"Dice 1: {dice1} \nDice 2: {dice2}")
        
        if dice1 == '1' and dice2 == '1': #both die = 1 (banked & running = 0)
            player1Score = 0
            rTotal = 0
            print("DOUBLE ONE! Banked total reset, Player 2's turn.")
            break
            
        elif dice1 == '1' or dice2 == '1': #either die = 1 (running = 0)
            rTotal = 0
            print("Rolled a single one. Player 2's turn!")
            break
                
        else: #normal dice roll - gamble or bank
            choice = input("Gamble (G) or Bank (B): ")
            choice = choice.upper() #incase lowercase letter given
                
            if choice == 'G': #if Gamble chosen - reroll dice & add to running
                rTotal += int(dice1) + int(dice2)
    
            elif choice == 'B': #used to save score.
                rTotal += int(dice1) + int(dice2)
                player1Score += rTotal
                print(f"\nPlayer 1 banked! Total: {player1Score}")
                break
    print("Turn over")

I have tried changing the 'or' in the while loop to an 'and'. While that did stop faster, it did not stop exactly as the other player achieved a score higher than 10.


Solution

  • What I did is inside the function put an if statement (outside of the while) to return a value from the function using return like this:

    def exampleFunction1():
        #scoring logic here
        if bank > finalScore: #Score to reach to win game
            print(f"Score is over {finalScore}!")
            return 0
    

    Then inside the while loop, attach the functions to a variable so that the return value could be identified. Use the return value to break the while loop:

    while True: #Breaks as soon as either player gets above 100 score
        x = exampleFunction1()
        if x == 0:
            break
        x = exampleFunction2()
        if x == 0:
            break
    

    (Sidenote: I rewrote my whole program to take one gameLogic() function and apply this to the different players, but I still used the while loop stated second)