Guest User

matchsticks_game

a guest
Feb 16th, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. class MatchsticksGame:
  2. def __init__(self, players=('Player 1', 'Player 2'), initial_matchsticks=23):
  3. self.players = players
  4. self.player = None
  5. self.turn = 0
  6. self.matchsticks = initial_matchsticks
  7.  
  8. def _current_player(self):
  9. return self.players[self.turn % 2]
  10.  
  11. def _show_matchsticks(self):
  12. return '||||| '*(self.matchsticks//5) + '|'*(self.matchsticks%5)
  13.  
  14. def get_move(self, player):
  15. while True:
  16. try:
  17. matchsticks_to_remove = int(input(f'{player} removes matchsticks: '))
  18.  
  19. if 1 <= matchsticks_to_remove <= 3:
  20. return matchsticks_to_remove
  21.  
  22. print('You can delete only between 1 and 3 matchsticks.')
  23. except ValueError:
  24. print('The value entered is invalid. You can only enter numeric values.')
  25.  
  26. def _play_turn(self):
  27. self.player = self._current_player()
  28. self.turn += 1
  29.  
  30. def _game_finished(self):
  31. return self.matchsticks <= 0
  32.  
  33. def play(self):
  34. print('Game starts.')
  35. print(self._show_matchsticks())
  36.  
  37. while self.matchsticks > 0:
  38. self._play_turn()
  39. matchsticks_to_remove = self.get_move(self.player)
  40. self.matchsticks -= matchsticks_to_remove
  41. print(self._show_matchsticks())
  42.  
  43. if self._game_finished():
  44. print(f'{self.player} is eliminated.')
  45. break
  46.  
  47.  
  48. if __name__ == '__main__':
  49. game = MatchsticksGame()
  50. game.play()
Advertisement
Add Comment
Please, Sign In to add comment