board.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import numpy as np
  2. class Board:
  3. MAX_BLOB = 255
  4. DECREASE_BLOB = 0.1
  5. def __init__(self, width, height):
  6. self.width = width
  7. self.height = height
  8. self.board_array = np.empty(shape=(width, height), dtype=object)
  9. for x in range(self.width):
  10. for y in range(self.height):
  11. self.board_array[x, y] = Square()
  12. def save(self):
  13. stream = ''
  14. for y in range(self.height):
  15. for x in range(self.width):
  16. saved_node = self.board_array[x, y].save() + " "
  17. stream += str(saved_node)
  18. stream = stream.rstrip(' ')
  19. stream += '\n'
  20. return stream.rstrip('\n')
  21. def load(self, file):
  22. y = 0
  23. for line in file:
  24. nodes = line.split(' ')
  25. if len(nodes) != self.width:
  26. print("Error with initialized height !" + str(len(nodes)))
  27. x = 0
  28. for node in nodes:
  29. self.board_array[x, y].load(node)
  30. x += 1
  31. y += 1
  32. def has_food(self, x, y):
  33. return self.inside(x, y) and self.board_array[x, y].food
  34. def update_blob(self, x, y, change_value):
  35. if self.inside(x, y):
  36. self.board_array[x, y].update_blob(change_value)
  37. return True
  38. else:
  39. return False
  40. def get_blob(self, x, y):
  41. if self.inside(x, y):
  42. return self.board_array[x, y].blob
  43. else:
  44. return None
  45. def inside(self, x, y):
  46. return 0 <= x < self.width and 0 <= y < self.height
  47. def is_touched(self, x, y):
  48. if self.inside(x, y):
  49. return self.board_array[x, y].touched
  50. else:
  51. return False
  52. def next_turn(self, food_lock=True):
  53. for x in range(self.width):
  54. for y in range(self.height):
  55. if self.board_array[x, y].touched:
  56. if not (food_lock and self.board_array[x,y].food):
  57. self.board_array[x, y].update_blob(-Board.DECREASE_BLOB)
  58. def reset(self, x, y):
  59. if self.inside(x, y):
  60. self.board_array[x, y] = Square()
  61. class Square:
  62. def __init__(self):
  63. self.food = False
  64. self.touched = False
  65. self.blob = 0
  66. def update_blob(self, change_value):
  67. self.touched = True
  68. self.blob += change_value
  69. self.blob = max(0, min(self.blob, Board.MAX_BLOB))
  70. def save(self):
  71. return format(self.touched, 'd') + "," + format(self.food, 'd') + "," + str(self.blob)
  72. def load(self, node):
  73. values = node.split(',')
  74. if len(values) != 3:
  75. print("Error with packaged values !")
  76. self.touched = values[0] == '1'
  77. self.food = values[1] == '1'
  78. self.blob = float(values[2])