조건이 충족 된 후 내 프로그램을 종료하는 방법이 있습니까? (플레이어가 게임에서이긴 경우)

Aug 19 2020

저는 약 일주일 전에 파이썬을 배웠지 만 (프로그래밍 경험이 없습니다) 뱀과 사다리 게임을 다시 만들려고했습니다. 코드를 작성했지만 플레이어가 이기면 프로그램을 종료하는 방법을 모릅니다. 플레이어가이긴 후에도 (100 개 또는 임의의 보드 크기) 내 프로그램은 여전히 ​​다른 플레이어에게 주사위를 굴려달라고 요청하고 게임은 계속됩니다.

내가 만든 Player 클래스는 다음과 같습니다. 에서 승리 조건을 찾을 수 있습니다 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()

답변

3 Hedy Aug 19 2020 at 08:03
elif new_position == board_size:
    print(f'{self.name} won')
    sys.exit(0)

에 기억 import sys파일의 상단에