refine.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import cv2
  2. from simulation.board import Board
  3. from simulation.player import Player
  4. def simulate(discrete_img, discrete_blob, discrete_food_list, config, refine=None):
  5. height, width = discrete_blob.shape
  6. board = Board(width, height)
  7. player = Player(board, None, "simulation/default/player.json")
  8. player.food_size = compute_discrete_food_size(config, player.use_circle)
  9. player.clean_top = refine['Clean Top'] if refine is not None else True
  10. for (x, y) in discrete_food_list:
  11. if board.is_touched(x, y):
  12. # TODO Set up value
  13. board.set_food(x, y, value=Board.INIT_FOOD/2)
  14. else:
  15. board.set_food(x, y)
  16. for x in range(width):
  17. for y in range(height):
  18. if discrete_blob[y, x] != 0:
  19. board.update_blob(x, y, discrete_blob[y, x])
  20. if refine is not None:
  21. adapt_food(board, player, config, refine)
  22. return board, player, discrete_img
  23. def adapt_food(board, player, config, refine):
  24. square_size = round(1 / refine["Width"] * config["Discrete Width"])
  25. adding_food = 0
  26. for food_origin in refine["Foods"]:
  27. discrete_food = (int(food_origin[0] / refine["Width"] * config["Discrete Width"]),
  28. int(food_origin[1] / refine["Height"] * config["Discrete Height"]))
  29. food_found = False
  30. for i in range(square_size):
  31. for j in range(square_size):
  32. if board.has_food(discrete_food[0] + i, discrete_food[1] + j):
  33. food_found = True
  34. if not food_found:
  35. # TODO Set up value
  36. player.set_food(round(discrete_food[0] + square_size/2), round(discrete_food[1] + square_size/2),
  37. force=True, value=Board.INIT_FOOD/4)
  38. adding_food += 1
  39. print("Foods added: {}".format(adding_food))
  40. def save(filename, board, player, img):
  41. with open(filename + ".board", 'w') as file:
  42. file.write(board.save())
  43. with open(filename + ".player.json", 'w') as file:
  44. file.write(player.save())
  45. cv2.imwrite(filename + ".jpg", img)
  46. def compute_discrete_food_size(config, use_circle=False):
  47. food_size = config["Min Food Size"]
  48. limits = config["Limits"]
  49. x_min = limits[0][0]
  50. x_max = limits[0][0]
  51. y_min = limits[0][1]
  52. y_max = limits[0][1]
  53. for limit in limits:
  54. x_min = min(x_min, limit[0])
  55. x_max = max(x_max, limit[0])
  56. y_min = min(y_min, limit[1])
  57. y_max = max(y_max, limit[1])
  58. img_width = x_max - x_min
  59. img_height = y_max - y_min
  60. if use_circle:
  61. ratio = 1.5 # ~sqrt(2)
  62. else:
  63. ratio = 1
  64. discrete_food_size = round((food_size / img_height * config["Discrete Height"]
  65. + food_size / img_width * config["Discrete Width"]) * ratio / 2)
  66. return discrete_food_size