cool0011

Untitled

Jan 22nd, 2020
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.97 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. def input_number(prompt='Please enter a number: ', minimum=0, maximum=None):
  5. """Read a positive number with the given prompt."""
  6.  
  7. while True:
  8. try:
  9. number = int(input(prompt))
  10. if (number < minimum or
  11. (maximum is not None and number > maximum)):
  12. print('Number is not within range: {} to {}'.format(minimum, maximum))
  13. else:
  14. break
  15.  
  16. except ValueError:
  17. print('You need to enter a number')
  18. continue
  19.  
  20. return number
  21.  
  22.  
  23. class RolledOneException(Exception):
  24. pass
  25.  
  26.  
  27. class Die:
  28. """A die to play with."""
  29.  
  30. def __init__(self):
  31. self.value = random.randint(1, 6)
  32.  
  33. def roll(self):
  34. """Returns the rolled dice, or raises RolledOneException if 1."""
  35.  
  36. self.value = random.randint(1, 6)
  37. if self.value == 1:
  38. raise RolledOneException
  39.  
  40. return self.value
  41.  
  42.  
  43. def __str__(self):
  44. return "Rolled " + str(self.value) + "."
  45.  
  46. class Box:
  47. """Temporary score box holder class."""
  48.  
  49. def __init__(self):
  50. self.value = 0
  51.  
  52.  
  53. def reset(self):
  54. self.value = 0
  55.  
  56.  
  57. def add_dice_value(self, dice_value):
  58. self.value += dice_value
  59.  
  60.  
  61. class Player(object):
  62. """Base class for different player types."""
  63.  
  64. def __init__(self, name=None):
  65. self.name = name
  66. self.score = 0
  67.  
  68.  
  69. def add_score(self, player_score):
  70. """Adds player_score to total score."""
  71.  
  72. self.score += player_score
  73.  
  74.  
  75. def __str__(self):
  76. """Returns player name and current score."""
  77.  
  78. return str(self.name) + ": " + str(self.score)
  79.  
  80.  
  81. class ComputerPlayer(Player):
  82. cpu_names=['Eliza', 'BigBlue', 'Foo', 'Bar']
  83.  
  84.  
  85. def __init__(self, number):
  86. """Assigns a cpu name from cpu_names, or Cpu#."""
  87.  
  88. if number < len(self.cpu_names):
  89. name = self.cpu_names[number]
  90. else:
  91. name = 'Cpu{}'.format(number)
  92.  
  93. super(ComputerPlayer, self).__init__(name)
  94.  
  95.  
  96. def keep_rolling(self, box):
  97. """Randomly decides if the CPU player will keep rolling."""
  98.  
  99. while box.value < (10 + random.randint(1, 35)):
  100. print(" CPU will roll again.")
  101. return True
  102. print(" CPU will hold.")
  103. return False
  104.  
  105.  
  106. class HumanPlayer(Player):
  107. def __init__(self, name):
  108. super(HumanPlayer, self).__init__(name)
  109.  
  110.  
  111. def keep_rolling(self, box):
  112. """Asks the human player, if they want to keep rolling."""
  113.  
  114. human_decision = input_number(" 1 - Roll again, 0 - Hold? ", 0, 1)
  115. if human_decision == 1:
  116. return True
  117. else:
  118. return False
  119.  
  120.  
  121. class GameManager:
  122. def __init__(self, humans=1, computers=1):
  123. """Initialises the game, optionally asking for human player names."""
  124.  
  125. self.players = []
  126. if humans == 1:
  127. self.players.append(HumanPlayer('Human'))
  128. else:
  129. for i in range(humans):
  130. player_name = input('Enter name of human player no. {}: '.format(i))
  131. self.players.append(HumanPlayer(player_name))
  132.  
  133. for i in range(computers):
  134. self.players.append(ComputerPlayer(i))
  135.  
  136. self.no_of_players = len(self.players)
  137.  
  138. self.die = Die()
  139. self.box = Box()
  140.  
  141.  
  142. @staticmethod
  143. def welcome():
  144. """Prints a welcome message including rules."""
  145.  
  146. print("*" * 70)
  147. print("Welcome to Pig Dice!" .center(70))
  148. print("*" * 70)
  149. print("The objective is to be the first to reach 100 points." .center(70))
  150. print("On each turn, the player will roll a die." .center(70))
  151. print("The die value will stored in a temporary score box." .center(70))
  152. print("(If the die value is 1, the player earns no points," .center(70))
  153. print("and the turn goes to the next player.)" .center(70))
  154. print("A human player has an option to either roll again," .center(70))
  155. print("or hold. If you hold, the score in the" .center(70))
  156. print("temporary box will be added to your total score." .center(70))
  157. print(" Good luck! " .center(70, "*"))
  158. print(" Remember " .center(70, "*"))
  159. print(" Fortune favors the brave... " .center(70, "*"))
  160. print(" but chance favors the smart! " .center(70, "*"))
  161. print()
  162. print("I will now decide who starts" .center(70, " "))
  163. print()
  164.  
  165.  
  166. def decide_first_player(self):
  167. """Randomly chooses a player to begin, and prints who is starting."""
  168.  
  169. self.current_player = random.randint(1, self.no_of_players) % self.no_of_players
  170.  
  171. print('{} starts'.format(self.players[self.current_player].name))
  172.  
  173.  
  174. def next_player(self):
  175. """Advanced self.current_player to next player."""
  176. self.current_player = (self.current_player + 1) % self.no_of_players
  177.  
  178.  
  179.  
  180. def previous_player(self):
  181. """Changes self.current_player to previous player."""
  182.  
  183. self.current_player = (self.current_player - 1) % self.no_of_players
  184.  
  185.  
  186. def get_all_scores(self):
  187. """Returns a join all players scores."""
  188.  
  189. return ', '.join(str(player) for player in self.players)
  190.  
  191.  
  192. def play_game(self):
  193. """Plays an entire game."""
  194.  
  195. self.welcome()
  196. self.decide_first_player()
  197.  
  198. while all(player.score < 100 for player in self.players):
  199. print('\nCurrent score --> {}'.format(self.get_all_scores()))
  200. print('\n*** {} to play ***'.format(self.players[self.current_player].name))
  201. self.box.reset()
  202.  
  203. while self.keep_rolling():
  204. pass
  205.  
  206. self.players[self.current_player].add_score(self.box.value)
  207. self.next_player()
  208.  
  209. ## The previous player has won...
  210. self.previous_player()
  211. print(' {} has won '.format(self.players[self.current_player].name).center(70, '*'))
  212.  
  213.  
  214. def keep_rolling(self):
  215. """Adds rolled dice to box. Returns if human/cpu wants to continue.
  216.  
  217. If either player rolls a 1, the box value is reset, and turn ends.
  218. """
  219. try:
  220. dice_value = self.die.roll()
  221. self.box.add_dice_value(dice_value)
  222. print('Last roll: {}, new box value: {}'.format(dice_value, self.box.value))
  223.  
  224. # Check if human (by asking) or computer(calculating) will keep rolling
  225. return self.players[self.current_player].keep_rolling(self.box)
  226.  
  227. except RolledOneException:
  228. print(' Rolled one. Switching turns')
  229. self.box.reset()
  230. return False
  231.  
  232.  
  233. def main():
  234. human_players = input_number('How many human players? ')
  235. computer_players = input_number('How many computer players? ')
  236.  
  237. game_manager = GameManager(human_players, computer_players)
  238. game_manager.play_game()
  239.  
  240.  
  241. if __name__ == '__main__':
  242. main()
Add Comment
Please, Sign In to add comment