Dice Simulator


SUBMITTED BY: Guest

DATE: July 11, 2014, 2:42 a.m.

FORMAT: Text only

SIZE: 3.1 kB

HITS: 604

  1. #!/usr/bin/python3
  2. # Dice simulator. Project for http://redd.it/2aaeou
  3. # author: wukaem
  4. import random
  5. DICE_SEGMENTS = {
  6. 0: ' .-------.',
  7. 1: ' | |',
  8. 2: ' | O |',
  9. 3: ' | O |',
  10. 4: ' | O |',
  11. 5: ' | O O |',
  12. 6: ' | O O O |',
  13. 7: " '-------'",
  14. }
  15. SIDE_REPR = (
  16. (0, 1, 2, 1, 7),
  17. (0, 3, 1, 4, 7),
  18. (0, 4, 2, 3, 7),
  19. (0, 5, 1, 5, 7),
  20. (0, 5, 2, 5, 7),
  21. (0, 6, 1, 6, 7),
  22. )
  23. def dice_img_lst(side):
  24. img_lst = []
  25. for segment_num in SIDE_REPR[side-1]:
  26. img_lst.append(DICE_SEGMENTS[segment_num])
  27. return img_lst
  28. def roll_dice(num):
  29. return [random.randint(1, 6) for _ in range(num)]
  30. def dice_image(dice_lst):
  31. dice_lst_img = []
  32. for side in dice_lst:
  33. dice_lst_img.append(dice_img_lst(side))
  34. rows = []
  35. for i in range(5):
  36. rows.append(''.join(segment[i] for segment in dice_lst_img))
  37. return '\n'.join(rows)
  38. def ask_question1():
  39. print('\nHow many dice do you want to roll? (1-5)')
  40. while True:
  41. ans = input('> ')
  42. try:
  43. ans = int(ans)
  44. except ValueError:
  45. print('\nGive me a number. Try again.')
  46. continue
  47. if ans in range(1, 6):
  48. return ans
  49. print('\nRoll at least 1 dice and no more than 5. Try again.')
  50. def ask_question2(num):
  51. question = ("Type 'q' to quit, 'c' to change number of dice,\n"
  52. "or hit <Enter> to roll {} dice again.".format(num))
  53. print(question)
  54. new_num = 0
  55. while not new_num:
  56. ans = input('> ')
  57. if ans == '':
  58. new_num = num
  59. elif ans.lower()[0] not in ('q', 'c'):
  60. print('Wrong answer.\n')
  61. print(question)
  62. continue
  63. elif ans.lower()[0] == 'q':
  64. new_num = -1
  65. else:
  66. new_num = ask_question1()
  67. return new_num
  68. def main():
  69. print('\n Welcome to DICE SIMULATOR')
  70. no_dice = ask_question1()
  71. while no_dice != -1:
  72. print('\n Rolling {} dice:\n'.format(no_dice))
  73. dice_list = roll_dice(no_dice)
  74. print(dice_image(dice_list))
  75. print('\n Total: {}\n'.format(sum(dice_list)))
  76. no_dice = ask_question2(no_dice)
  77. print('Goodbye!')
  78. if __name__ == "__main__": main()

comments powered by Disqus