CMU Coding Bootcamp

feat: oct 1 level 4

thecoded.prof 62599897 ed475f62

verified
+92
+92
python/oct1/level4/playThreeDiceYahtzee.py
··· 1 + def handToDice(hand: int) -> tuple[int, int, int]: 2 + """Converts a hand to a tuple of dice.""" 3 + return hand // 100, (hand // 10) % 10, hand % 10 4 + 5 + 6 + def diceToOrderedHand(a: int, b: int, c: int) -> int: 7 + """Converts a tuple of dice to an ordered hand.""" 8 + ordered = sorted([a, b, c]) 9 + return ordered[2] * 100 + ordered[1] * 10 + ordered[0] 10 + 11 + 12 + def playStep2(hand: int, dice: int) -> tuple[int, int]: 13 + """ 14 + If you don't have 3 matching dice: 15 + If you have a pair: keep the pair and reroll the third 16 + Else: Roll all dice again 17 + """ 18 + (a, b, c) = handToDice(hand) 19 + if a == b and b == c: 20 + return hand, dice 21 + if a == b: 22 + c = dice % 10 23 + dice //= 10 24 + elif b == c: 25 + a = dice % 10 26 + dice //= 10 27 + elif a == c: 28 + b = dice % 10 29 + dice //= 10 30 + else: 31 + b = dice % 10 32 + dice //= 10 33 + c = dice % 10 34 + dice //= 10 35 + return diceToOrderedHand(a, b, c), dice 36 + 37 + 38 + def score(hand: int) -> int: 39 + """ 40 + Calculate the score of a hand 41 + 3 dice match: 20 + highest value * 3 42 + 2 dice match: 10 + highest value * 2 43 + 1 dice match: highest value 44 + """ 45 + (a, b, c) = handToDice(hand) 46 + if a == b and b == c: 47 + return 20 + a * 3 48 + elif a == b: 49 + return 10 + a * 2 50 + elif b == c: 51 + return 10 + b * 2 52 + elif a == c: 53 + return 10 + c * 2 54 + else: 55 + return a 56 + 57 + 58 + def playThreeDiceYahtzee(dice: int) -> tuple[int, int]: 59 + """Play a game of Three Dice Yahtzee""" 60 + a = dice % 10 61 + dice //= 10 62 + b = dice % 10 63 + dice //= 10 64 + c = dice % 10 65 + dice //= 10 66 + hand = diceToOrderedHand(a, b, c) 67 + hand, dice = playStep2(hand, dice) 68 + hand, dice = playStep2(hand, dice) 69 + return hand, score(hand) 70 + 71 + 72 + print("Testing playThreeDiceYahtzee()...", end="") 73 + assert handToDice(123) == (1, 2, 3) 74 + assert handToDice(214) == (2, 1, 4) 75 + assert handToDice(422) == (4, 2, 2) 76 + 77 + assert diceToOrderedHand(1, 2, 3) == 321 78 + assert diceToOrderedHand(1, 4, 2) == 421 79 + 80 + assert playStep2(413, 2312) == (421, 23) 81 + assert playStep2(544, 23) == (443, 2) 82 + assert playStep2(544, 456) == (644, 45) 83 + 84 + assert score(432) == 4 85 + assert score(443) == 10 + 4 + 4 86 + assert score(633) == 10 + 3 + 3 87 + assert score(555) == 20 + 5 + 5 + 5 88 + 89 + assert playThreeDiceYahtzee(2312413) == (432, 4) 90 + assert playThreeDiceYahtzee(2633413) == (633, 16) 91 + assert playThreeDiceYahtzee(2333555) == (555, 35) 92 + print("Passed!")