#!/usr/bin/env python3
#Advent of Code
#2022 Day 2, Part 1
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classShape:def__init__(self,letter):matchletter:case"A"|"X":self.shape="rock"self.score=1case"B"|"Y":self.shape="paper"self.score=2case"C"|"Z":self.shape="scissors"self.score=3defbeats(self,opponent):matchself.shape:case"rock":returnopponent.shape=="scissors"case"paper":returnopponent.shape=="rock"case"scissors":returnopponent.shape=="paper"def__eq__(self,other):returnself.shape==other.shapedefround_outcome(opponent,player):opponent=Shape(opponent)player=Shape(player)ifopponent.beats(player):# The opponent's move wins
return0elifopponent==player:# It's a tie
return3else:# The player's move wins
return6returnsum(Shape(player).score+round_outcome(opponent,player)foropponent,playerin[turn.split()forturninpuzzle_input])defmain():puzzle_input=util.read.as_lines()score=solve(puzzle_input)print("The total score is "+str(score)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve(["A Y","B X","C Z"]),15)if__name__=="__main__":run(main)
#!/usr/bin/env python3
#Advent of Code
#2022 Day 2, Part 2
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classShape:def__init__(self,letter):matchletter:case"A"|"rock":self.shape="rock"self.score=1self.wins_to="scissors"self.loses_to="paper"case"B"|"paper":self.shape="paper"self.score=2self.wins_to="rock"self.loses_to="scissors"case"C"|"scissors":self.shape="scissors"self.score=3self.wins_to="paper"self.loses_to="rock"defbeats(self,opponent):returnself.wins_to==opponent.shapedef__eq__(self,other):returnself.shape==other.shapedefround_outcome(opponent,player):ifopponent.beats(player):# The opponent's move wins
return0elifopponent==player:# It's a tie
return3else:# The player's move wins
return6total=0forturninpuzzle_input:opponent,desired_outcome=turn.split()opponent=Shape(opponent)matchdesired_outcome:case"X":# Need to lose
# Play the move that the opponent beats
player=Shape(opponent.wins_to)case"Y":# Need to tie
# Play the same move as the opponent
player=opponentcase"Z":# Need to win
# Play the move that beats the opponent, i.e. the move that the opponent is beaten by
player=Shape(opponent.loses_to)total+=player.score+round_outcome(opponent,player)returntotaldefmain():puzzle_input=util.read.as_lines()score=solve(puzzle_input)print("The total score is "+str(score)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve(["A Y","B X","C Z"]),12)if__name__=="__main__":run(main)