Design a two-player game with three core methods:
add_score(player)get_score()get_result()The game should keep track of the score for each player and provide a human-readable tennis-style format for the current score.
add_score(player) method should take a player identifier (e.g., "player1" or "player2") and update the score accordingly.get_score() method should return the current score in the format {player1_score}:{player2_score}.get_result() method should return the result of the game in a human-readable format if one player has won, or indicate that the game is still ongoing.Convert the score into a human-readable tennis-style format, such as "15-30", "40-40", "Advantage player1", "Game player1", etc.
Here is a possible implementation of the Tennis Score Game in Python:
`python class TennisGame: def init(self, player1, player2): self.player1 = player1 self.player2 = player2 self.score1 = 0 self.score2 = 0
def add_score(self, player):
if player == self.player1:
self.score1 += 1
elif player == self.player2:
self.score2 += 1
def get_score(self):
score1 = self.convert_score(self.score1)
score2 = self.convert_score(self.score2)
return f"{score1}-{score2}"
def get_result(self):
if self.score1 == self.score2:
if self.score1 < 3:
return f"{self.score1 * 15}-{self.score2 * 15}"
else:
return "Deuce"
elif self.score1 >= 4 and self.score1 - self.score2 >= 2:
return "Win for player1"
elif self.score2 >= 4 and self.score2 - self.score1 >= 2:
return "Win for player2"
else:
return "Advantage " + (self.player1 if self.score1 > self.score2 else self.player2)
def convert_score(self, score):
if score == 0:
return "Love"
elif score == 1:
return "15"
elif score == 2:
return "30"
elif score == 3:
return "40"
else:
return "Advantage " + (self.player1 if score == 4 else self.player2)
game = TennisGame("player1", "player2") game.add_score("player1") game.add_score("player1") game.add_score("player2") print(game.get_score()) # Output: 30-15 print(game.get_result()) # Output: Advantage player1 `
This implementation covers the basic functionality and follows the rules of tennis scoring. The convert_score method is used to convert numerical scores into their tennis-style equivalents.