LifeContainer.gd 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. extends Node2D
  2. var living_cells = {}
  3. var default_font
  4. const label_offset = Vector2(5, 15)
  5. const cell_size = Vector2(40, 20)
  6. const rect_pad = Vector2(3, 3)
  7. func spawn_brick(x, y, maximum_life):
  8. living_cells[Vector2(x, y)] = randi() % maximum_life + 1
  9. update()
  10. func may_die_by_taking_this(pos, damage):
  11. var has_died = false
  12. if damage > 0 and living_cells.has(pos):
  13. living_cells[pos] -= damage
  14. update()
  15. has_died = living_cells[pos] <= 0
  16. if has_died:
  17. living_cells.erase(pos)
  18. return has_died
  19. func create_font():
  20. var label = Label.new()
  21. default_font = label.get_font("font")
  22. func color_from_life(n):
  23. var x = float(n % 256) / 255
  24. if (n < 256):
  25. return Color(x, 1.0, 1.0 - x)
  26. elif (n < 512):
  27. return Color(1.0, 1.0 - x, x)
  28. elif (n < 768):
  29. return Color(1.0, 0.0, 1.0 - x)
  30. else:
  31. return Color(1.0, 0.0, 0.0)
  32. func _ready():
  33. create_font()
  34. func _draw():
  35. var amount
  36. var pos
  37. var color
  38. for cell in living_cells:
  39. pos = cell * cell_size
  40. amount = living_cells[cell]
  41. color = color_from_life(amount)
  42. draw_rect(Rect2(pos + rect_pad, cell_size - 2 * rect_pad), color, true)
  43. draw_string(default_font, pos + label_offset, str(amount))