Search code examples
pythonterminate

Is there a way to terminate my program after a condition is met? (If a player won the game)


I just learned Python about a week ago (I don't have any programming experience), but I tried to recreate the snakes and ladders game. I coded it but I don't know how to terminate the program if a player won. After a player has won (reached 100 or any board size), my program still asks another player to roll the dice and the game just continues.

Here is the Player class I created. You can find the win condition in Player.turn().

class Player:
    def __init__(self, name):
        self.name = str(name)
        self.position = int()

    def ask_to_roll(self):
        while True:
            command = str(input("Press enter to roll the dice.\n> "))
            if command == "":
                break
            else:
                print("Invalid")
                continue

    def roll_dice(self):
        print(f'{self.name} is rolling the dice...')
        time.sleep(delay)
        roll_result = random.randint(1, dice_faces)
        print(f"It's a {roll_result}!")
        time.sleep(delay)
        return roll_result

    def check_for_snakes_ladders(self):
        if self.position in snakes.keys():
            print(random.choice(snake_bite))
            time.sleep(delay)
            print(f'{self.name} fell from {self.position} to {snakes[self.position]}')
            time.sleep(delay)
            self.position = snakes[self.position]
        elif self.position in ladders.keys():
            print(random.choice(ladder_jump))
            time.sleep(delay)
            print(f'{self.name} climbed from {self.position} to {ladders[self.position]}')
            time.sleep(delay)
            self.position = ladders[self.position]
        else:
            pass

    def turn(self):
        print(f"\nIt's {self.name}'s turn")
        self.ask_to_roll()
        roll_result = self.roll_dice()
        new_position = self.position + roll_result
        if new_position > board_size:
            print(f"Oops you need to get {board_size - self.position}")
            pass
        elif new_position == board_size:
            print(f'{self.name} won')*
        elif new_position < board_size:
            print(f'{self.name} moved from {self.position} to {new_position}')
            time.sleep(delay)
            self.position = new_position
            self.check_for_snakes_ladders()

Solution

  • elif new_position == board_size:
        print(f'{self.name} won')
        sys.exit(0)
    

    Remember to import sys at the top of the file