IT/Python

[Python] 요트다이스 (Yacht)

잿호 2023. 10. 2. 21:15
- 실행 예시 -

     


    설계

    1. 보드게임 요트다이스를 파이썬으로 구현했다.

    2. 다인용 게임인 요트다이스와 다르게 1인용으로 구현했다.

    3. 점수표는 아래 참조


    점수표

     

    Ones
    1이 나온 주사위 눈의 총합. 최대 5점.
     = 3점

    Twos
    2가 나온 주사위 눈의 총합. 최대 10점.
    = 6점

    Threes
    3이 나온 주사위 눈의 총합. 최대 15점.
     = 9점

    Fours
    4가 나온 주사위 눈의 총합. 최대 20점.
     = 12점

    Fives
    5가 나온 주사위 눈의 총합. 최대 25점.
     = 15점

    Sixes
    6이 나온 주사위 눈의 총합. 최대 30점.
     = 18점

    Three of a Kind
    동일한 주사위 눈이 3개 이상일 때,
    동일한 주사위 눈 3개의 총합. 최대 18점.
     = 18점

    Four of a Kind
    동일한 주사위 눈이 4개 이상일 때,
    동일한 주사위 눈 4개의 총합. 최대 24점.
     = 24점

    Full House
    동일한 주사위 눈 한 종류가 3개, 다른 종류가 2개일 때,
    주사위 눈 5개의 총합. 최대 28점.
     = 28점

    Small Straight
    주사위 눈이 각각 1, 2, 3, 4 or 2, 3, 4, 5 or 3, 4, 5, 6일 때. 고정 30점.
     = 30점

    Large Straight
    주사위 눈이 각각 1, 2, 3, 4, 5 or 2, 3, 4, 5, 6일 때. 고정 30점.
     = 30점

    Yacht
    동일한 주사위 눈이 5개일 때. 고정 50점.
     = 50점

    Chance
    주사위 눈 5개의 총합. 최대 30점.
     = 24점
     

    코드

    import random
    total_category = []
    # 1 - 6 사이의 랜덤 숫자 리턴
    def roll_die():
        return random.randint(1, 6)
    
    # 1 - 6사이의 숫자중 겹칠 수 있는 6개의 숫자를 반환
    def roll_dice():
        return [roll_die() for _ in range(5)]
    
    # 숫자별 갯수를 세어준다
    def count_dice(dice):
        counts = {}
        for die in dice:
            if die in counts:
                counts[die] += 1
            else:
                counts[die] = 1
        return counts
    
    # 족보를 판단하여 점수를 반환
    def score_category(dice, category):
        counts = count_dice(dice)
        
        if category == "Ones":
            total_category.append("Ones")
            return counts.get(1, 0) * 1
        elif category == "Twos":
            total_category.append("Twos")
            return counts.get(2, 0) * 2
        elif category == "Threes":
            total_category.append("Threes")
            return counts.get(3, 0) * 3
        elif category == "Fours":
            total_category.append("Fours")
            return counts.get(4, 0) * 4
        elif category == "Fives":
            total_category.append("Fives")
            return counts.get(5, 0) * 5
        elif category == "Sixes":
            total_category.append("Sixes")
            return counts.get(6, 0) * 6
        elif category == "Three of a Kind":
            for die, count in counts.items():
                if count >= 3:
                    total_category.append("Three of a Kind")
                    return sum(die for _ in range(3))
            total_category.append("Three of a Kind")
            return 0
        elif category == "Four of a Kind":
            for die, count in counts.items():
                if count >= 4:
                    total_category.append("Four of a Kind")
                    return sum(die for _ in range(4))
            total_category.append("Four of a Kind")
            return 0
        elif category == "Full House":
            if len(counts) == 2 and 2 in counts.values() and 3 in counts.values():
                total_category.append("Full House")
                return 25
            total_category.append("Full House")
            return 0
        elif category == "Small Straight":
            if sorted(counts.keys()) in [[1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 6], [2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6], [1, 3, 4, 5, 6]]:
                total_category.append("Small Straight")
                return 30
            total_category.append("Small Straight")
            return 0
        elif category == "Large Straight":
            if sorted(counts.keys()) == [1, 2, 3, 4, 5] or sorted(counts.keys()) == [2, 3, 4, 5, 6]:
                total_category.append("Large Straight")
                return 40
            total_category.append("Large Straight")
            return 0
        elif category == "Yacht":
            if len(counts) == 1:
                total_category.append("Yacht")
                return 50
            total_category.append("Yacht")
            return 0
        elif category == "Chance":
            total_category.append("Chance")
            return sum(dice)
        else:
            print("다시 입력 부탁해요")
            return "again"
    
    # 굴린 다이스의 결과를 노출
    def display_dice(dice):
        print("다이스:", dice)
    
    # 유지를 택한 주사위를 제외한 나머지를 랜덤값으로 돌려준다.
    def reroll_random(lendice):
        random_count = 5 - lendice
        return [roll_die() for _ in range(random_count)]
    
    # 유지 할 다이스 선택
    def dice_reroll(dice):
        while(True):
            stay_dice = ''  
            stay_dice = input("유지할 다이스 선택 : ")
            if stay_dice == '':
                return roll_dice()
            list_stay_dice = stay_dice.split(sep=',')
            list_stay_dice = list(map(int, list_stay_dice))
            if len(list_stay_dice) == 5:
                return list_stay_dice
            if (set(list_stay_dice) & set(dice)) == set(list_stay_dice):
                return_reroll = reroll_random(len(list_stay_dice))
                list_stay_dice.extend(return_reroll)
                return list_stay_dice
            else:
                print("잘못된 입력입니다.(보유하지 않은 다이스)")
    
    # 족보 중복 확인
    def check_category():
        category = input("점수를 입력할 족보를 선택 : ")   
        while(category in total_category):
            
            print("이미 입력한 족보입니다!")
            print(total_category)
            category = input("점수를 입력할 족보를 선택 : ") 
        return category
        
    # n턴 진행 
    def play_turn():
        dice = roll_dice()
        display_dice(dice)
        for i in range(3):
            dice = dice_reroll(dice)
            display_dice(dice)
            
        print()
        display_dice(dice)   
        category = check_category() 
        score = score_category(dice, category)
        while(score == "again"):
            category = check_category() 
            score = score_category(dice, category)
            
        if score == 0:
            print("족보가 없거나 점수가 0 입니다.")
        else:
            print(f"Score for {category}: {dice}")
    
        return score
    
    # 요트다이스 메인
    def play_yacht_dice():
        print("요트 다이스 시작!")
        total_score = 0
        for _ in range(13):
            print(f"턴 {_ + 1}:")
            score = play_turn()
            total_score += score
            print(f"총 점수: {total_score}\n")
        print(f"최종 점수: {total_score}")
    
    if __name__ == "__main__":
        play_yacht_dice()

     

     

     


    실행

     

    01234567891011
    - 실행 과정 -

     


    실행 (PC)

     

     

     

     


    마무리

    모두 즐거운 추석 되셨나요? 저도 블로그를 잠시 쉬면서 집에서 늘어져 있었습니다.

    코딩 재활겸 긴 코드를 작성해봤습니다.

    추석에 윷놀이를 즐겼던 보드게임의 민족인 만큼 요트다이스 코딩도 추석 특별활동이라고 쳐도 될까요? .,ㅎㅎ

     

    23-10-09 | 이미지가 깨지는 현상이 있어서 수정했습니다.

    반응형