Advertisement
Guest User

mastermind

a guest
Oct 19th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.71 KB | None | 0 0
  1. import pygame
  2. import random
  3.  
  4. DEBUG_accelerate_loss = False
  5. DEBUG_temp = None
  6.  
  7. pygame.init()  # initialize modules
  8. # pygame.font.init()
  9.  
  10. # window dimensions
  11. screen_width = 300
  12. screen_height = 600
  13.  
  14.  
  15. def horizontal_center(dimension):
  16.     return (screen_width - dimension) // 2
  17.  
  18.  
  19. def vertical_center(dimension):
  20.     return (screen_height - dimension) // 2
  21.  
  22.  
  23. def cursor_in_region(coor_tuple, dim_tuple, mcoor_tuple):
  24.     mx, my = mcoor_tuple[0], mcoor_tuple[1]
  25.     xlo = coor_tuple[0]
  26.     xhi = coor_tuple[0] + dim_tuple[0]
  27.     ylo = coor_tuple[1]
  28.     yhi = coor_tuple[1] + dim_tuple[1]
  29.     boo = xlo <= mx <= xhi and ylo <= my <= yhi
  30.     print(boo)
  31.     return boo
  32.  
  33.  
  34. def render_end(is_game_won):
  35.     end_str = "YOU LOSE!!"
  36.     if is_game_won:
  37.         end_str = "YOU WIN!!"
  38.  
  39.     game_screen.fill(black)
  40.     # UI post-game display
  41.     attempt = score_font.render("Guesses: {}".format(no_of_guess), True, gray)
  42.     lose_message = game_font.render(end_str, True, gray)
  43.     play_again_message = score_font.render("Play Again", True, gray)
  44.  
  45.     aw = attempt.get_rect().width
  46.     game_screen.blit(attempt, (horizontal_center(aw), screen_height * (1 / 7)))
  47.     lmw = lose_message.get_rect().width
  48.     game_screen.blit(lose_message, (horizontal_center(lmw), screen_height * (1.5 / 7)))
  49.     pamw = play_again_message.get_rect().width
  50.     pamh = play_again_message.get_rect().height
  51.     pamy = screen_height * (3 / 7)
  52.     pampadding = 25
  53.     pabcoor[0], pabcoor[1] = horizontal_center(pamw) - pampadding, pamy - pampadding
  54.     pabdim[0], pabdim[1] = pamw + 2 * pampadding, pamh + 2 * pampadding
  55.     pygame.draw.rect(game_screen,
  56.                      dark_gray, (
  57.                          pabcoor[0],
  58.                          pabcoor[1],
  59.                          pabdim[0],
  60.                          pabdim[1]))
  61.     game_screen.blit(play_again_message, (horizontal_center(pamw), pamy))
  62.  
  63.  
  64. def calculate_grid_dimensions(colors, columns=3, cell_size=50, cell_spacing=10):
  65.     row = 0
  66.     grid_x = (cell_size + cell_spacing) * columns
  67.     color = 0
  68.     while color < len(colors):
  69.         col = 0
  70.         while col < columns:
  71.             col += 1
  72.             color += 1
  73.         row += 1
  74.     grid_y = (cell_size + cell_spacing) * row
  75.     return grid_x, grid_y
  76.  
  77.  
  78. def render_color_grid(interface, x, y, colors, columns=3, cell_size=50, cell_spacing=10):
  79.     """
  80.    Renders a 3x3 grid of colors. This function is particular to this program.
  81.    :param interface: Surface wherein the function will write the grid
  82.    :param x: X coordinate
  83.    :param y: Y coordinate
  84.    :param colors: The list of colors to be used
  85.    :param columns: 3 by default. The number of columns in the grid
  86.    :param cell_size: 50 by default. The size of each individual cell in the grid.
  87.    :param cell_spacing: 10 by default. The distance between all cells.
  88.    :return: Tuple containing the x and y dimensions of the grid
  89.    """
  90.     row = 0
  91.     grid_x = (cell_size + cell_spacing) * columns
  92.     color = 0
  93.     while color < len(colors):
  94.         col = 0
  95.         while col < columns:
  96.             pygame.draw.rect(interface,
  97.                              colors[color],
  98.                              (
  99.                                  x + (cell_size * col) + (cell_spacing * col),
  100.                                  y + (cell_size * row) + (cell_spacing * row),
  101.                                  cell_size,
  102.                                  cell_size
  103.                              )
  104.                              )
  105.             col += 1
  106.             color += 1
  107.         row += 1
  108.     grid_y = (cell_size + cell_spacing) * row
  109.     return grid_x, grid_y
  110.  
  111.  
  112. def calculate_row_dimensions(colors, cell_size=50, cell_spacing=10):
  113.     return len(colors) * (cell_size + cell_spacing), cell_size
  114.  
  115.  
  116. def render_color_row(interface, x, y, colors, cell_size=50, cell_spacing=10):
  117.     for c in range(len(colors)):
  118.         pygame.draw.rect(interface,
  119.                          colors[c],
  120.                          (
  121.                              x + (cell_size * c) + (cell_spacing * c),
  122.                              y,
  123.                              cell_size,
  124.                              cell_size
  125.                          )
  126.                          )
  127.  
  128.  
  129. # colors
  130. black = (0, 0, 0, 255)
  131. white = (255, 255, 255, 255)
  132. gray = (128, 128, 128, 255)
  133. dark_gray = (50, 50, 50, 255)
  134. red = (255, 0, 0, 255)
  135. green = (0, 255, 0, 255)
  136. blue = (0, 0, 255, 255)
  137. yellow = (255, 255, 0, 255)
  138. orange = (255, 165, 0, 255)
  139. purple = (128, 0, 128, 255)
  140. maroon = (128, 0, 0, 255)
  141. pink = (255, 105, 80, 255)
  142. brown = (139, 69, 19, 255)
  143.  
  144. # color translation
  145. color_directory = {
  146.     # black: "black",
  147.     # white: "white",
  148.     gray: "gray",
  149.     red: "red",
  150.     green: "green",
  151.     blue: "blue",
  152.     yellow: "yellow",
  153.     orange: "orange",
  154.     purple: "purple",
  155.     maroon: "maroon",
  156.     pink: "pink",
  157.     brown: "brown"
  158. }
  159.  
  160. # color list
  161. color_list = [
  162.     red,
  163.     green,
  164.     blue,
  165.     yellow,
  166.     orange,
  167.     purple,
  168.     maroon,
  169.     pink,
  170.     brown,
  171. ]
  172.  
  173. # initialization block
  174. i = 1
  175. guess_list = []
  176. ans_list = []
  177. black_count = 0
  178. white_count = 0
  179. no_of_guess = 0
  180. is_win = 0  # 0: in-game, 1: Win, -1: Loss, -2: Waiting
  181. keys = pygame.key.get_pressed()  # list of all keyboard keys
  182. display_bottom_screen = guess_processed = False
  183.  
  184. # UI block
  185. game_screen = pygame.display.set_mode((screen_width, screen_height))
  186. pygame.display.set_caption("MasterMind")
  187. game_font = pygame.font.SysFont('Segoe UI Light', 60)
  188. score_font = pygame.font.SysFont('Segoe UI Light', 40)
  189. reminder_font = pygame.font.SysFont('Segoe UI Light', 40)
  190. display_text = game_font.render('MasterMind', False, white)
  191. clock = pygame.time.Clock()
  192.  
  193. header_y_offset = 100
  194. color_grid_y_offset = -50
  195. guess_list_y_offset = 100
  196. guess_number_y = screen_height - 100
  197. score_y = screen_height - 50
  198.  
  199. # play again button dimensions and coordinates
  200. pabdim = [0, 0]
  201. pabcoor = [0, 0]
  202.  
  203.  
  204. def init_game():
  205.     global i, black_count, white_count, no_of_guess, is_win, display_bottom_screen
  206.     print("[DEBUG] Game resetting...")
  207.     is_win = -2
  208.     i = 1
  209.     guess_list.clear()
  210.     ans_list.clear()
  211.     black_count = 0
  212.     white_count = 0
  213.     no_of_guess = 0
  214.     display_bottom_screen = False
  215.  
  216.     # randomization block
  217.     for x in range(4):  # loops from 1 to no_of_colors
  218.         randomized_int = random.randint(0, 8)
  219.         ans_list.append(color_list[randomized_int])  # 1 to 9
  220.         print("Randomized Integer: {}".format(randomized_int))
  221.         print("Appended color to answer: {}".format(color_directory[color_list[randomized_int]]))
  222.     print("DEBUG")
  223.     [print(color_directory[i], end=" ") for i in ans_list]
  224.     print()
  225.     is_win = 0
  226.     print("[DEBUG] Game reset.")
  227.  
  228.  
  229. init_game()
  230. print("[DEBUG] ans_list: {}".format(ans_list))
  231.  
  232.  
  233. def render_game():
  234.     if is_win == -2:
  235.         game_screen.fill(black)
  236.     elif is_win == 0:
  237.  
  238.         game_screen.fill(dark_gray)  # black background
  239.  
  240.         # title
  241.         dtxd = display_text.get_rect().width  # display text x dimension
  242.         game_screen.blit(display_text, (horizontal_center(dtxd), header_y_offset))
  243.  
  244.         # color grid
  245.         cgd = calculate_grid_dimensions(color_list)  # color grid dimensions
  246.         render_color_grid(game_screen, horizontal_center(cgd[0]), vertical_center(cgd[1]) + color_grid_y_offset,
  247.                           color_list)
  248.  
  249.         # guess list
  250.         grd = calculate_row_dimensions(guess_list, cell_size=25)  # guess row dimensions
  251.         render_color_row(game_screen, horizontal_center(grd[0]), vertical_center(grd[1]) + guess_list_y_offset,
  252.                          guess_list, cell_size=25)
  253.  
  254.         if len(guess_list) == 4:
  255.             guess_display = score_font.render("Guess #{}:".format(no_of_guess), True, white)
  256.             score = score_font.render(
  257.                 "{black}B - {white}W".format(black=black_count, white=white_count),
  258.                 True, white)
  259.  
  260.             gdw = guess_display.get_rect().width
  261.             game_screen.blit(guess_display, (horizontal_center(gdw), guess_number_y))
  262.             sw = score.get_rect().width
  263.             game_screen.blit(score, (horizontal_center(sw), score_y))
  264.     elif is_win == -1:
  265.         render_end(False)
  266.     elif is_win == 1:
  267.         render_end(True)
  268.  
  269.  
  270. # main game loop
  271. execute = True
  272. while execute:
  273.     # Render the game
  274.     render_game()
  275.     pygame.display.update()
  276.     if no_of_guess >= 12:
  277.         print("Loss.")
  278.         print("is_win == -1")
  279.         is_win = -1
  280.     # event block
  281.     for event in pygame.event.get():  # loop through user events i.e. keyboard, mouse
  282.         if event.type == pygame.QUIT:  # exit button
  283.             execute = False
  284.         if event.type == pygame.MOUSEBUTTONDOWN:
  285.             # Do the following events over the course of the game:
  286.             if is_win == 0:
  287.                 # Start waiting
  288.                 if len(guess_list) >= 4:
  289.                     guess_list = []
  290.                     black_count = 0
  291.                     white_count = 0
  292.                     guess_processed = False
  293.  
  294.                 print("[DEBUG] Mouse Clicked.")
  295.                 i += 1
  296.  
  297.                 print("[DEBUG] Number of guesses: {}".format(no_of_guess))
  298.                 color_under_cursor = game_screen.get_at(pygame.mouse.get_pos())
  299.                 color_under_cursor = tuple(color_under_cursor)
  300.                 print("[DEBUG] Color under cursor: {}".format(color_under_cursor))
  301.                 if color_under_cursor in color_directory:
  302.                     print("[DEBUG] Color guessed: {}".format(color_directory[color_under_cursor]))
  303.                     guess_list.append(color_under_cursor)
  304.                 print("[DEBUG] guess_list: {}".format(guess_list))
  305.  
  306.                 DEBUG_temp = (len(guess_list) == 4 and not guess_processed)
  307.                 print("[DEBUG] len(guess_list) == 4 and not guess_processed: {}".format(DEBUG_temp))
  308.                 if len(guess_list) == 4 and not guess_processed:
  309.                     [print(color_directory[i], end=" ") for i in guess_list]
  310.                     print()
  311.                     no_of_guess += 1
  312.                     print("[DEBUG] ans_list: {}".format(ans_list))
  313.                     print("[DEBUG] guess_list: {}".format(guess_list))
  314.                     # process guess
  315.                     for ans, guess in list(zip(ans_list, guess_list)):
  316.                         print("[DEBUG] {} == {}: {}".format(ans, guess, ans == guess))
  317.                         if ans == guess:
  318.                             black_count += 1
  319.                             print("[DEBUG] Incremented black count. Count is now {}".format(black_count))
  320.                         print("[DEBUG] guess in ans_list: {}".format(guess in ans_list))
  321.                         if guess in ans_list:
  322.                             white_count += 1
  323.                             print("[DEBUG] Incremented white count. Count is now {}".format(white_count))
  324.  
  325.                     if black_count == 4 and white_count == 4:
  326.                         print("Guess #{}:".format(no_of_guess))
  327.                         print("4B - 4W")
  328.                         print("Win.")
  329.                         print("is_win = 1")
  330.                         is_win = 1
  331.                     else:
  332.                         print("Guess #{}:".format(no_of_guess))
  333.                         print("{black}B - {white}W".format(black=black_count, white=white_count))
  334.  
  335.                     guess_processed = True
  336.             # Do the following actions during game end prompt
  337.             else:
  338.                 c_in_rgn = cursor_in_region(pabcoor, pabdim, pygame.mouse.get_pos())
  339.                 print("[DEBUG] cursor in region: ".format(c_in_rgn))
  340.                 if c_in_rgn:
  341.                     init_game()
  342.  
  343.     clock.tick(60)  # sets fps
  344.     pygame.time.delay(500)  # allows
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement