interface.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import pygame
  2. import time
  3. import datetime
  4. import os.path
  5. import json
  6. from pygame.locals import *
  7. from simulation.board import Board
  8. class Interface:
  9. FOOD_COLOR = (0, 150, 0)
  10. TOUCHED_COLOR = (50, 50, 0)
  11. BLOB_LOWER_COLOR = (255, 255, 0)
  12. BLOB_HIGHER_COLOR = (255, 0, 0)
  13. BACKGROUND = (0, 0, 0)
  14. BOARD_SEPARATOR = (120, 120, 120)
  15. def __init__(self, board, player, blob, scale, save_dir, mode, hidden=False, colors_file=None):
  16. """
  17. :type board: Board
  18. :type player: Player
  19. :type blob: Blob_Manager
  20. :type scale: float
  21. :type save_dir: str
  22. """
  23. pygame.init()
  24. # pygame.key.set_repeat(5, 50)
  25. if colors_file is not None:
  26. with open(colors_file, 'r') as file:
  27. colors = json.load(file)
  28. Interface.FOOD_COLOR = tuple(colors['FOOD_COLOR'])
  29. Interface.TOUCHED_COLOR = tuple(colors['TOUCHED_COLOR'])
  30. Interface.BLOB_LOWER_COLOR = tuple(colors['BLOB_LOWER_COLOR'])
  31. Interface.BLOB_HIGHER_COLOR = tuple(colors['BLOB_HIGHER_COLOR'])
  32. Interface.BACKGROUND = tuple(colors['BACKGROUND'])
  33. Interface.BOARD_SEPARATOR = tuple(colors['BOARD_SEPARATOR'])
  34. self.board = board
  35. self.player = player
  36. self.blob = blob
  37. self.scale = scale
  38. self.save_dir = save_dir
  39. self.debug_mode = False
  40. self.play = False
  41. self.do_step = False
  42. self.show_ants = True
  43. width = self.board.width * scale
  44. height = self.board.height * scale
  45. self.hidden = hidden
  46. if not self.hidden:
  47. self.window = pygame.display.set_mode((width, height), mode)
  48. self.window_surface = pygame.Surface((width, height))
  49. cross_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cross.png")
  50. discovered_food = pygame.image.load(cross_file)
  51. if not self.hidden:
  52. discovered_food = discovered_food.convert()
  53. discovered_food.set_colorkey((255, 255, 255))
  54. self.discovered_food = pygame.transform.scale(discovered_food, (scale, scale))
  55. def draw(self):
  56. width = self.board.width * self.scale
  57. height = self.board.height * self.scale
  58. game_surface = pygame.Surface((self.board.width, self.board.height))
  59. pixel_array = pygame.PixelArray(game_surface)
  60. for x in range(self.board.width):
  61. for y in range(self.board.height):
  62. pixel_array[x, y] = Interface.BACKGROUND
  63. if self.board.has_food(x, y):
  64. pixel_array[x, y] = Interface.FOOD_COLOR
  65. if self.board.is_touched(x, y):
  66. pixel_array[x, y] = Interface.TOUCHED_COLOR
  67. val = self.board.get_blob(x, y)
  68. if val != Board.MIN_BLOB:
  69. val = (val - Board.MIN_BLOB) / (Board.MAX_BLOB - Board.MIN_BLOB)
  70. red = (Interface.BLOB_HIGHER_COLOR[0] - Interface.BLOB_LOWER_COLOR[0]) * val + \
  71. Interface.BLOB_LOWER_COLOR[0]
  72. green = (Interface.BLOB_HIGHER_COLOR[1] - Interface.BLOB_LOWER_COLOR[1]) * val + \
  73. Interface.BLOB_LOWER_COLOR[1]
  74. blue = (Interface.BLOB_HIGHER_COLOR[2] - Interface.BLOB_LOWER_COLOR[2]) * val + \
  75. Interface.BLOB_LOWER_COLOR[2]
  76. pixel_array[x, y] = (red, green, blue)
  77. if self.show_ants:
  78. for scouter in self.blob.scouters:
  79. pixel_array[scouter.x, scouter.y] = (255, 255, 255)
  80. del pixel_array
  81. game_window = pygame.transform.scale(game_surface, (width, height))
  82. pygame.draw.line(game_window, Interface.BOARD_SEPARATOR, (0, height / 2), (width, height / 2))
  83. self.window_surface.blit(game_window, (0, 0))
  84. for food in self.blob.knowledge['food']:
  85. self.window_surface.blit(self.discovered_food, (food[0] * self.scale, food[1] * self.scale))
  86. if not self.hidden:
  87. self.window.blit(self.window_surface, (0, 0))
  88. pygame.display.flip()
  89. def save(self, name=None):
  90. if name is None:
  91. name = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H.%M.%S')
  92. print("Data saved at " + name)
  93. f = open(self.save_dir + name + ".board", 'w')
  94. f.write(self.board.save())
  95. f.close()
  96. f = open(self.save_dir + name + ".blob.json", 'w')
  97. f.write(self.blob.save())
  98. f.close()
  99. f = open(self.save_dir + name + ".player.json", 'w')
  100. f.write(self.player.save())
  101. f.close()
  102. if self.hidden:
  103. self.draw()
  104. pygame.image.save(self.window_surface, self.save_dir + name + ".jpg")
  105. return name
  106. def event_listener(self, event):
  107. # ADMIN ACTIONS
  108. if event.type == KEYDOWN and event.key == 100: # D Letter
  109. self.debug_mode = not self.debug_mode
  110. print("Debug Mode: " + str(self.debug_mode))
  111. elif event.type == KEYDOWN and event.key == K_UP:
  112. self.blob.knowledge["Global Decrease"] += 0.1
  113. print("Pheromone evaporation : " + str(self.blob.knowledge["Global Decrease"]))
  114. elif event.type == KEYDOWN and event.key == K_DOWN:
  115. self.blob.knowledge["Global Decrease"] -= 0.1
  116. print("Pheromone evaporation : " + str(self.blob.knowledge["Global Decrease"]))
  117. elif event.type == KEYDOWN and event.key == K_SPACE:
  118. self.show_ants = not self.show_ants
  119. elif event.type == KEYDOWN and event.key == 115: # S Letter
  120. self.save()
  121. # DEBUG ACTIONS
  122. elif self.debug_mode and event.type == MOUSEBUTTONDOWN and event.button == 1: # Right Click
  123. x = int(pygame.mouse.get_pos()[0] / self.scale)
  124. y = int(pygame.mouse.get_pos()[1] / self.scale)
  125. self.board.update_blob(x, y, 10)
  126. # PLAYER ACTIONS
  127. elif event.type == MOUSEBUTTONDOWN and event.button == 1: # Right Click
  128. x = int(pygame.mouse.get_pos()[0]/self.scale)
  129. y = int(pygame.mouse.get_pos()[1]/self.scale)
  130. if self.board.has_food(x, y):
  131. self.player.remove_food(x, y)
  132. else:
  133. self.player.set_food(x, y)
  134. elif event.type == KEYDOWN and event.key == 99: # C Letter
  135. self.player.clean_board()
  136. elif event.type == KEYDOWN and event.key == 114: # R Letter
  137. self.player.set_random_food(10, not self.player.clean_top)
  138. elif event.type == KEYDOWN and event.key == 104: # H Letter
  139. up_size_percent, down_size_percent = self.player.check_blob_cover()
  140. print("Blob covering:")
  141. print("\t{:.2f}% of the board.".format((up_size_percent + down_size_percent)/2))
  142. print("\t{:.2f}% of the upper board.".format(up_size_percent))
  143. print("\t{:.2f}% of the lower board.".format(down_size_percent))
  144. # BLOB ACTIONS
  145. elif event.type == KEYDOWN and event.key == 112: # P Letter
  146. self.play = not self.play
  147. elif event.type == KEYDOWN and event.key == K_RETURN:
  148. self.do_step = True
  149. elif event.type == KEYDOWN and event.key == 107: # K Letter
  150. if self.blob.knowledge["Scouters"]["Min"] > 0:
  151. self.blob.knowledge["Scouters"]["Min"] -= 1
  152. print("New minimal scouters : " + str(self.blob.knowledge["Scouters"]["Min"]) + " - Currently : "
  153. + str(len(self.blob.scouters)))
  154. elif event.type == KEYDOWN and event.key == 113: # A letter
  155. self.blob.knowledge["Scouters"]["Min"] += 1
  156. print("New minimal scouters : " + str(self.blob.knowledge["Scouters"]["Min"]) + " - Currently : "
  157. + str(len(self.blob.scouters)))
  158. elif event.type == KEYDOWN:
  159. print("Unrecognised key code : " + str(event.key))
  160. return False
  161. else:
  162. return False
  163. return True