Legend of the Gold Box... A game written for the LOWREZJAM 2018 game jam
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

927 lines
31KB

  1. '''
  2. Filename nodes.py
  3. Author: Bryan "ObsidianBlk" Miller
  4. Date Created: 8/1/2018
  5. Python Version: 3.7
  6. '''
  7. from .display import Display
  8. from .events import Events
  9. from .resource import ResourceManager
  10. import pygame
  11. class NodeError(Exception):
  12. pass
  13. class Node:
  14. def __init__(self, name="Node", parent=None):
  15. self._NODE_DATA={
  16. "parent":None,
  17. "name":name,
  18. "children":[],
  19. "resource":None,
  20. "position":(0,0)
  21. }
  22. if parent is not None:
  23. try:
  24. self.parent = parent
  25. except NodeError as e:
  26. raise e
  27. @property
  28. def parent(self):
  29. return self._NODE_DATA["parent"]
  30. @parent.setter
  31. def parent(self, new_parent):
  32. try:
  33. self.parent_to_node(new_parent)
  34. except NodeError as e:
  35. raise e
  36. @property
  37. def root(self):
  38. if self.parent is None:
  39. return self
  40. return self.parent.root
  41. @property
  42. def name(self):
  43. return self._NODE_DATA["name"]
  44. @name.setter
  45. def name(self, value):
  46. if self.parent is not None:
  47. if self.parent.get_node(value) is not None:
  48. raise NodeError("Parent already contains node named '{}'.".format(name))
  49. self._NODE_DATA["name"] = value
  50. @property
  51. def full_name(self):
  52. if self.parent is None:
  53. return self.name
  54. return self.parent.full_name + "." + self.name
  55. @property
  56. def resource(self):
  57. if self._NODE_DATA["resource"] is None:
  58. # Only bother creating the instance if it's being asked for.
  59. # All ResourceManager instances access same data.
  60. self._NODE_DATA["resource"] = ResourceManager()
  61. return self._NODE_DATA["resource"]
  62. @property
  63. def child_count(self):
  64. return len(self._NODE_DATA["children"])
  65. @property
  66. def position(self):
  67. p = self._NODE_DATA["position"]
  68. return (p[0], p[1])
  69. @position.setter
  70. def position(self, pos):
  71. if not isinstance(pos, (list, tuple)):
  72. raise TypeError("Expected a list or tuple.")
  73. if len(pos) != 2:
  74. raise ValueError("Wrong number of values given.")
  75. try:
  76. self.position_x = pos[0]
  77. self.position_y = pos[1]
  78. except Exception as e:
  79. raise e
  80. @property
  81. def position_x(self):
  82. return self._NODE_DATA["position"][0]
  83. @position_x.setter
  84. def position_x(self, v):
  85. if not isinstance(v, (int, float)):
  86. raise TypeError("Excepted an number value.")
  87. self._NODE_DATA["position"] = (float(v), self._NODE_DATA["position"][1])
  88. @property
  89. def position_y(self):
  90. return self._NODE_DATA["position"][1]
  91. @position_y.setter
  92. def position_y(self, v):
  93. if not isinstance(v, (int, float)):
  94. raise TypeError("Excepted an number value.")
  95. self._NODE_DATA["position"] = (self._NODE_DATA["position"][0], float(v))
  96. def get_world_position(self):
  97. if self.parent is None:
  98. return (0,0)
  99. pos = self.position
  100. ppos = self.parent.get_world_position()
  101. return (pos[0] + ppos[0], pos[1] + ppos[1])
  102. def parent_to_node(self, parent, allow_reparenting=False):
  103. if not isinstance(parent, Node):
  104. raise NodeError("Node may only parent to another Node instance.")
  105. if self.parent is None or self.parent != parent:
  106. if self.parent is not None:
  107. if allow_Reparenting == False:
  108. raise NodeError("Node already assigned a parent Node.")
  109. if self.parent.remove_node(self) != self:
  110. raise NodeError("Failed to remove self from current parent.")
  111. try:
  112. parent.attach_node(self)
  113. except NodeError as e:
  114. raise e
  115. def attach_node(self, node, reparent=False, index=-1):
  116. if node.parent is not None:
  117. if node.parent == self:
  118. return # Nothing to do. Given node already parented to this node.
  119. if reparent == False:
  120. raise NodeError("Node already parented.")
  121. if node.parent.remove_node(node) != node:
  122. raise NodeError("Failed to remove given node from it's current parent.")
  123. if self.get_node(node.name) is not None:
  124. raise NodeError("Node with name '{}' already attached.".format(node.name))
  125. node._NODE_DATA["parent"] = self
  126. children = self._NODE_DATA["children"]
  127. if index < 0 or index >= len(children):
  128. children.append(node)
  129. else:
  130. children.insert(index, node)
  131. def remove_node(self, node):
  132. if isinstance(node, (str, unicode)):
  133. n = self.get_node(node)
  134. if n is not None:
  135. try:
  136. return self.remove_node(n)
  137. except NodeError as e:
  138. raise e
  139. elif isinstance(node, Node):
  140. if node.parent != self:
  141. if node.parent == None:
  142. raise NodeError("Cannot remove an unparented node.")
  143. try:
  144. return node.parent.remove_node(node)
  145. except NodeError as e:
  146. raise e
  147. if node in self._NODE_DATA["children"]:
  148. self._NODE_DATA["children"].remove(node)
  149. node._NODE_DATA["parent"] = None
  150. return node
  151. else:
  152. raise NodeError("Expected a Node instance or a string.")
  153. return None
  154. def get_node(self, name):
  155. if self.child_count <= 0:
  156. return None
  157. subnames = name.split(".")
  158. for c in self._NODE_DATA["children"]:
  159. if c.name == subnames[0]:
  160. if len(subnames) > 1:
  161. return c.get_node(".".join(subnames[1:-1]))
  162. return c
  163. return None
  164. def listen(self, signal, callback_fn):
  165. try:
  166. Events.listen(signal, callback_fn)
  167. except Exception as e:
  168. raise e
  169. def unlisten(self, signal, callback_fn):
  170. Events.unlisten(signal, callback_fn)
  171. def emit(self, signal, data={}):
  172. # NOTE: I'm currently forcing the existance of this "NODE" key in the dictionary given. Not sure if I'll keep this.
  173. data["NODE"] = {
  174. "name":self.name,
  175. "n":self
  176. }
  177. Events.emit(signal, data)
  178. def _init(self):
  179. if hasattr(self, "on_init"):
  180. self.on_init()
  181. for c in self._NODE_DATA["children"]:
  182. c._init()
  183. def _close(self):
  184. if hasattr(self, "on_close"):
  185. self.on_close()
  186. for c in self._NODE_DATA["children"]:
  187. c._close()
  188. def _pause(self):
  189. if hasattr(self, "on_pause"):
  190. self.on_pause()
  191. for c in self._NODE_DATA["children"]:
  192. c._pause()
  193. def _start(self):
  194. if hasattr(self, "on_start"):
  195. self.on_start()
  196. for c in self._NODE_DATA["children"]:
  197. c._start()
  198. def _update(self, dt):
  199. if hasattr(self, "on_update"):
  200. self.on_update(dt)
  201. for c in self._NODE_DATA["children"]:
  202. c._update(dt)
  203. def _render(self, surface):
  204. for c in self._NODE_DATA["children"]:
  205. c._render(surface)
  206. class Node2D(Node):
  207. def __init__(self, name="Node2D", parent=None):
  208. try:
  209. Node.__init__(self, name, parent)
  210. except NodeError as e:
  211. raise e
  212. @property
  213. def resolution(self):
  214. p = self.parent
  215. # We don't directly have the answer, but maybe our parent does?
  216. if p is not None:
  217. if hasattr(p, "resolution"):
  218. return p.resolution
  219. # Otherwise the Display object should.
  220. return Display.resolution
  221. def _callOnRender(self, surface):
  222. if hasattr(self, "on_render"):
  223. self._ACTIVE_SURF = surface
  224. self.on_render()
  225. del self._ACTIVE_SURF
  226. def _render(self, surface):
  227. self._callOnRender(surface)
  228. Node._render(self, surface)
  229. def draw_image(self, img, pos=(0,0), rect=None):
  230. if not hasattr(self, "_ACTIVE_SURF"):
  231. return
  232. self._ACTIVE_SURF.blit(img, pos, rect)
  233. def fill(self, color):
  234. if not hasattr(self, "_ACTIVE_SURF"):
  235. return
  236. self._ACTIVE_SURF.fill(color)
  237. def draw_lines(self, points, color, thickness=1, closed=False):
  238. if not hasattr(self, "_ACTIVE_SURF"):
  239. return
  240. pygame.draw.lines(self._ACTIVE_SURF, color, closed, points, thickness)
  241. def draw_rect(self, rect, color, thickness=1, fill_color=None):
  242. if not hasattr(self, "_ACTIVE_SURF"):
  243. return
  244. if fill_color is not None:
  245. self._ACTIVE_SURF.fill(fill_color, rect)
  246. if thickness > 0:
  247. pygame.draw.rect(self._ACTIVE_SURF, color, rect, thickness)
  248. def draw_ellipse(self, rect, color, thickness=1, fill_color=None):
  249. if not hasattr(self, "_ACTIVE_SURF"):
  250. return
  251. if fill_color is not None:
  252. pygame.draw.ellipse(self._ACTIVE_SURF, fill_color, rect)
  253. if thickness > 0:
  254. pygame.draw.ellipse(self._ACTIVE_SURF, color, rect, thickness)
  255. def draw_circle(self, pos, radius, color, thickness=1, fill_color=None):
  256. if not hasattr(self, "_ACTIVE_SURF"):
  257. return
  258. if fill_color is not None:
  259. pygame.draw.circle(self._ACTIVE_SURF, fill_color, pos, radius)
  260. if thickness > 0:
  261. pygame.draw.circle(self._ACTIVE_SURF, color, pos, radius, thickness)
  262. def draw_polygon(self, points, color, thickness=1, fill_color=None):
  263. if not hasattr(self, "_ACTIVE_SURF"):
  264. return
  265. if fill_color is not None:
  266. pygame.draw.polygon(self._ACTIVE_SURF, fill_color, points)
  267. if thickness >= 1:
  268. pygame.draw.polygon(self._ACTIVE_SURF, color, points, thickness)
  269. class NodeSurface(Node2D):
  270. def __init__(self, name="NodeSurface", parent=None):
  271. try:
  272. Node2D.__init__(self, name, parent)
  273. except NodeError as e:
  274. raise e
  275. # TODO: Update this class to use the _NODE*_DATA={} structure.
  276. self._NODESURFACE_DATA={
  277. "clear_color":None
  278. }
  279. self._scale = (1.0, 1.0)
  280. self._scaleToDisplay = False
  281. self._scaleDirty = False
  282. self._keepAspectRatio = False
  283. self._alignCenter = False
  284. self._surface = None
  285. self._tsurface = None
  286. self.set_surface()
  287. def _updateTransformSurface(self):
  288. if self._surface is None:
  289. return
  290. self._scaleDirty = False
  291. if self._scaleToDisplay:
  292. dsize = Display.resolution
  293. ssize = self._surface.get_size()
  294. self._scale = (dsize[0] / ssize[0], dsize[1] / ssize[1])
  295. if self._keepAspectRatio:
  296. if self._scale[0] < self._scale[1]:
  297. self._scale = (self._scale[0], self._scale[0])
  298. else:
  299. self._scale = (self._scale[1], self._scale[1])
  300. if self._scale[0] == 1.0 and self._scale[1] == 1.0:
  301. self._tsurface = None
  302. return
  303. size = self._surface.get_size()
  304. nw = size[0] * self._scale[0]
  305. nh = 0
  306. if self._keepAspectRatio:
  307. nh = size[1] * self._scale[0]
  308. else:
  309. nh = size[1] * self._scale[1]
  310. self._tsurface = pygame.Surface((nw, nh), pygame.SRCALPHA, self._surface)
  311. self._tsurface.fill(pygame.Color(0,0,0,0))
  312. @property
  313. def resolution(self):
  314. if self._surface is None:
  315. return super().resolution
  316. return self._surface.get_size()
  317. @resolution.setter
  318. def resolution(self, res):
  319. try:
  320. self.set_surface(res)
  321. except (TypeError, ValueError) as e:
  322. raise e
  323. @property
  324. def width(self):
  325. return self.resolution[0]
  326. @property
  327. def height(self):
  328. return self.resolution[1]
  329. @property
  330. def scale(self):
  331. return self._scale
  332. @scale.setter
  333. def scale(self, scale):
  334. if self._keepAspectRatio:
  335. if not isinstance(scale, (int, float)):
  336. raise TypeError("Expected number value.")
  337. self._scale = (scale, self._scale[1])
  338. else:
  339. if not isinstance(scale, tuple):
  340. raise TypeError("Expected a tuple")
  341. if len(scale) != 2:
  342. raise ValueError("Expected tuple of length two.")
  343. if not isinstance(scale[0], (int, float)) or not isinstance(scale[1], (int, float)):
  344. raise TypeError("Expected number values.")
  345. self._scale = scale
  346. self._updateTransformSurface()
  347. @property
  348. def keep_aspect_ratio(self):
  349. return self._keepAspectRatio
  350. @keep_aspect_ratio.setter
  351. def keep_aspect_ratio(self, keep):
  352. self._keepAspectRatio = (keep == True)
  353. self._updateTransformSurface()
  354. @property
  355. def align_center(self):
  356. return self._alignCenter
  357. @align_center.setter
  358. def align_center(self, center):
  359. self._alignCenter = (center == True)
  360. @property
  361. def scale_to_display(self):
  362. return self._scaleToDisplay
  363. @scale_to_display.setter
  364. def scale_to_display(self, todisplay):
  365. if todisplay == True:
  366. self._scaleToDisplay = True
  367. Events.listen("VIDEORESIZE", self._OnVideoResize)
  368. else:
  369. self._scaleToDisplay = False
  370. Events.unlisten("VIDEORESIZE", self._OnVideoResize)
  371. self._updateTransformSurface()
  372. def scale_to(self, target_resolution):
  373. if self._surface is not None:
  374. size = self._surface.get_size()
  375. nscale = (float(size[0]) / float(target_resolution[0]), float(size[1]) / float(target_resolution[1]))
  376. self.scale = nscale
  377. def set_surface(self, resolution=None):
  378. dsurf = Display.surface
  379. if resolution is None:
  380. if dsurf is not None:
  381. self._surface = dsurf.convert_alpha()
  382. self._surface.fill(pygame.Color(0,0,0,0))
  383. self._updateTransformSurface()
  384. else:
  385. if not isinstance(resolution, tuple):
  386. raise TypeError("Expected a tuple.")
  387. if len(resolution) != 2:
  388. raise ValueError("Expected a tuple of length two.")
  389. if not isinstance(resolution[0], int) or not isinstance(resolution[1], int):
  390. raise TypeError("Tuple expected to contain integers.")
  391. if dsurf is not None:
  392. self._surface = pygame.Surface(resolution, pygame.SRCALPHA, dsurf)
  393. else:
  394. self._surface = pygame.Surface(resolution, pygame.SRCALPHA)
  395. self._surface.fill(pygame.Color(0,0,0,0))
  396. self._updateTransformSurface()
  397. def set_clear_color(self, color):
  398. if color is None:
  399. self._NODESURFACE_DATA["clear_color"] = None
  400. elif isinstance(color, (list, tuple)):
  401. clen = len(color)
  402. if clen == 3 or clen == 4:
  403. iscolor = lambda v: isinstance(v, int) and v >= 0 and v < 256
  404. if iscolor(color[0]) and iscolor(color[1]) and iscolor(color[2]):
  405. if clen == 3 or (clen == 4 and iscolor(color[3])):
  406. self._NODESURFACE_DATA["clear_color"] = pygame.Color(*color)
  407. def get_clear_color(self):
  408. cc = self._NODESURFACE_DATA["clear_color"]
  409. if cc == None:
  410. return None
  411. return (cc.r, cc.g, cc.b, cc.a)
  412. def _render(self, surface):
  413. if self._surface is None:
  414. self.set_surface()
  415. if self._surface is not None:
  416. if self._scaleDirty:
  417. self._updateTransformSurface()
  418. cc = self._NODESURFACE_DATA["clear_color"]
  419. if cc is not None:
  420. self._surface.fill(cc)
  421. Node2D._render(self, self._surface)
  422. else:
  423. Node2D._render(self, surface)
  424. self._scale_and_blit(surface)
  425. def _scale_and_blit(self, dest):
  426. dsize = dest.get_size()
  427. src = self._surface
  428. if self._tsurface is not None:
  429. pygame.transform.scale(self._surface, self._tsurface.get_size(), self._tsurface)
  430. src = self._tsurface
  431. ssize = src.get_size()
  432. posx = self.position_x
  433. posy = self.position_y
  434. if self._alignCenter:
  435. if dsize[0] > ssize[0]:
  436. posx += (dsize[0] - ssize[0]) * 0.5
  437. if dsize[1] > ssize[1]:
  438. posy += (dsize[1] - ssize[1]) * 0.5
  439. pos = (int(posx), int(posy))
  440. dest.blit(src, pos)
  441. def _OnVideoResize(self, event, data):
  442. if self._scaleToDisplay:
  443. self._scaleDirty = True
  444. class NodeText(Node2D):
  445. def __init__(self, name="NodeText", parent=None):
  446. try:
  447. Node2D.__init__(self, name, parent)
  448. except NodeError as e:
  449. raise e
  450. self._NODETEXT_DATA={
  451. "font_src":"",
  452. "size":26,
  453. "antialias":True,
  454. "color":pygame.Color(255,255,255),
  455. "background":None,
  456. "text":"Some Text",
  457. "surface":None
  458. }
  459. @property
  460. def font_src(self):
  461. return self._NODETEXT_DATA["font_src"]
  462. @font_src.setter
  463. def font_src(self, src):
  464. res = self.resource
  465. if src != "" and src != self._NODETEXT_DATA["font_src"] and res.is_valid("font", src):
  466. self._NODETEXT_DATA["font_src"] = src
  467. if not res.has("font", src):
  468. res.store("font", src)
  469. self._NODETEXT_DATA["surface"] = None
  470. @property
  471. def size(self):
  472. return self._NODETEXT_DATA["size"]
  473. @size.setter
  474. def size(self, size):
  475. if not isinstance(size, int):
  476. raise TypeError("Expected integer value.")
  477. if size <= 0:
  478. raise ValueError("Size must be greater than zero.")
  479. if size != self._NODETEXT_DATA["size"]:
  480. self._NODETEXT_DATA["size"] = size
  481. self._NODETEXT_DATA["surface"] = None
  482. @property
  483. def antialias(self):
  484. return self._NODETEXT_DATA["antialias"]
  485. @antialias.setter
  486. def antialias(self, enable):
  487. enable = (enable == True)
  488. if enable != self._NODETEXT_DATA["antialias"]:
  489. self._NODETEXT_DATA["antialias"] = enable
  490. self._NODETEXT_DATA["surface"] = None
  491. @property
  492. def text(self):
  493. return self._NODETEXT_DATA["text"]
  494. @text.setter
  495. def text(self, text):
  496. if text != self._NODETEXT_DATA["text"]:
  497. self._NODETEXT_DATA["text"] = text
  498. self._NODETEXT_DATA["surface"] = None
  499. def _setColor(self, cname, r, g, b, a):
  500. if r < 0 or r > 255:
  501. raise ValueError("Red value out of bounds.")
  502. if g < 0 or g > 255:
  503. raise ValueError("Green value out of bounds.")
  504. if b < 0 or b > 255:
  505. raise ValueError("Blue value out of bounds.")
  506. if a < 0 or a > 255:
  507. raise ValueError("Alpha value out of bounds.")
  508. color = self._NODETEXT_DATA[cname]
  509. if color.r != r or color.g != g or color.b != b or color.a != a:
  510. self._NODETEXT_DATA[cname] = pygame.Color(r,g,b,a)
  511. self._NODETEXT_DATA["surface"] = None
  512. def _getColor(self, cname):
  513. if self._NODETEXT_DATA[cname] is None:
  514. return (0,0,0,0)
  515. else:
  516. c = self._NODETEXT_DATA[cname]
  517. return (c.r, c.g, c.b, c.a)
  518. def set_color(self, r, g, b, a=255):
  519. try:
  520. self._setColor("color", r, g, b, a)
  521. except ValueError as e:
  522. raise e
  523. return self
  524. def get_color(self):
  525. return self._getColor("color")
  526. def set_background(self, r, g, b, a=255):
  527. try:
  528. self._setColor("background", r, g, b, a)
  529. except ValueError as e:
  530. raise e
  531. return self
  532. def clear_background(self):
  533. if self._NODETEXT_DATA["background"] is not None:
  534. self._NODETEXT_DATA["background"] = None
  535. self._NODETEXT_DATA["surface"] = None
  536. return self
  537. def get_background(self):
  538. c = self._getColor("background")
  539. if c[3] <= 0:
  540. return None
  541. return c
  542. def _render(self, surface):
  543. if self._NODETEXT_DATA["surface"] is None and self._NODETEXT_DATA["text"] != "":
  544. res = self.resource
  545. fnt = res.get("font", self._NODETEXT_DATA["font_src"], {"size":self._NODETEXT_DATA["size"]})
  546. if fnt is not None and fnt() is not None:
  547. surf = None
  548. try:
  549. text = self.text
  550. antialias = self.antialias
  551. color = self._NODETEXT_DATA["color"]
  552. background = self._NODETEXT_DATA["background"]
  553. surf = fnt().render(text, antialias, color, background)
  554. except pygame.error as e:
  555. pass # TODO: Update to send out warning!
  556. self._NODETEXT_DATA["surface"] = surf
  557. # We really don't want to keep the font instance around... just in case we want to use the same font at different sizes.
  558. res.clear("font", self._NODETEXT_DATA["font_src"])
  559. Node2D._render(self, surface)
  560. if self._NODETEXT_DATA["surface"] is not None:
  561. pos = self.position
  562. pos = (int(pos[0]), int(pos[1]))
  563. surface.blit(self._NODETEXT_DATA["surface"], pos)
  564. class NodeSprite(Node2D):
  565. def __init__(self, name="NodeSprite", parent=None):
  566. try:
  567. Node2D.__init__(self, name, parent)
  568. except NodeError as e:
  569. raise e
  570. self._NODESPRITE_DATA={
  571. "rect":[0,0,0,0],
  572. "image":"",
  573. "scale":[1.0, 1.0],
  574. "scale_dirty":True,
  575. "surface":None
  576. }
  577. @property
  578. def image_width(self):
  579. if self._NODESPRITE_DATA["surface"] is None:
  580. return 0
  581. surf = self._NODESPRITE_DATA["surface"]()
  582. return surf.get_width()
  583. @property
  584. def image_height(self):
  585. if self._NODESPRITE_DATA["surface"] is None:
  586. return 0
  587. surf = self._NODESPRITE_DATA["surface"]()
  588. return surf.get_height()
  589. @property
  590. def sprite_width(self):
  591. return int(self.rect_width * self.scale_x)
  592. @property
  593. def sprite_height(self):
  594. return int(self.rect_height * self.scale_y)
  595. @property
  596. def rect(self):
  597. return (self._NODESPRITE_DATA["rect"][0],
  598. self._NODESPRITE_DATA["rect"][1],
  599. self._NODESPRITE_DATA["rect"][2],
  600. self._NODESPRITE_DATA["rect"][3])
  601. @rect.setter
  602. def rect(self, rect):
  603. if not isinstance(rect, (list, tuple)):
  604. raise TypeError("Expected a list or tuple.")
  605. if len(rect) != 4:
  606. raise ValueError("rect value contains wrong number of values.")
  607. try:
  608. self.rect_x = rect[0]
  609. self.rect_y = rect[1]
  610. self.rect_width = rect[2]
  611. self.rect_height = rect[3]
  612. except Exception as e:
  613. raise e
  614. @property
  615. def rect_x(self):
  616. return self._NODESPRITE_DATA["rect"][0]
  617. @rect_x.setter
  618. def rect_x(self, v):
  619. if not isinstance(v, int):
  620. raise TypeError("Expected integer value.")
  621. self._NODESPRITE_DATA["rect"][0] = v
  622. self._NODESPRITE_ValidateRect()
  623. @property
  624. def rect_y(self):
  625. return self._NODESPRITE_DATA["rect"][1]
  626. @rect_y.setter
  627. def rect_y(self, v):
  628. if not isinstance(v, int):
  629. raise TypeError("Expected integer value.")
  630. self._NODESPRITE_DATA["rect"][1] = v
  631. self._NODESPRITE_ValidateRect()
  632. @property
  633. def rect_width(self):
  634. return self._NODESPRITE_DATA["rect"][2]
  635. @rect_width.setter
  636. def rect_width(self, v):
  637. if not isinstance(v, int):
  638. raise TypeError("Expected integer value.")
  639. self._NODESPRITE_DATA["rect"][2] = v
  640. self._NODESPRITE_ValidateRect()
  641. @property
  642. def rect_height(self):
  643. return self._NODESPRITE_DATA["rect"][3]
  644. @rect_height.setter
  645. def rect_height(self, v):
  646. if not isinstance(v, int):
  647. raise TypeError("Expected integer value.")
  648. self._NODESPRITE_DATA["rect"][3] = v
  649. self._NODESPRITE_ValidateRect()
  650. @property
  651. def center(self):
  652. r = self._NODESPRITE_DATA["rect"]
  653. return (int(r[0] + (r[2] * 0.5)), int(r[1] + (r[3] * 0.5)))
  654. @property
  655. def scale(self):
  656. return (self._NODESPRITE_DATA["scale"][0], self._NODESPRITE_DATA["scale"][1])
  657. @scale.setter
  658. def scale(self, scale):
  659. if not isinstance(scale, (list, tuple)):
  660. raise TypeError("Expected a list or tuple.")
  661. if len(scale) != 2:
  662. raise ValueError("Scale contains wrong number of values.")
  663. try:
  664. self.scale_x = scale[0]
  665. self.scale_y = scale[1]
  666. except Exception as e:
  667. raise e
  668. @property
  669. def scale_x(self):
  670. return self._NODESPRITE_DATA["scale"][0]
  671. @scale_x.setter
  672. def scale_x(self, v):
  673. if not isinstance(v, (int, float)):
  674. raise TypeError("Expected number value.")
  675. self._NODESPRITE_DATA["scale"][0] = float(v)
  676. self._NODESPRITE_DATA["scale_dirty"] = True
  677. @property
  678. def scale_y(self):
  679. return self._NODESPRITE_DATA["scale"][1]
  680. @scale_y.setter
  681. def scale_y(self, v):
  682. if not isinstance(v, (int, float)):
  683. raise TypeError("Expected number value.")
  684. self._NODESPRITE_DATA["scale"][1] = float(v)
  685. self._NODESPRITE_DATA["scale_dirty"] = True
  686. @property
  687. def image(self):
  688. return self._NODESPRITE_DATA["image"]
  689. @image.setter
  690. def image(self, src):
  691. src = src.strip()
  692. if self._NODESPRITE_DATA["image"] == src:
  693. return # Nothing to change... lol
  694. if self._NODESPRITE_DATA["image"] != "":
  695. self._NODESPRITE_DATA["surface"] = None # Clear reference to original surface.
  696. if src != "":
  697. rm = self.resource
  698. try:
  699. if not rm.has("graphic", src):
  700. rm.store("graphic", src)
  701. self._NODESPRITE_DATA["image"] = src
  702. self._NODESPRITE_DATA["surface"] = rm.get("graphic", src)
  703. if self._NODESPRITE_DATA["surface"] is None:
  704. self._NODESPRITE_DATA["image"] = ""
  705. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  706. else:
  707. # Resetting the rect to identity for the new image.
  708. surf = self._NODESPRITE_DATA["surface"]()
  709. size = surf.get_size()
  710. self._NODESPRITE_DATA["rect"]=[0,0,size[0], size[1]]
  711. except Exception as e:
  712. raise e
  713. else:
  714. self._NODESPRITE_DATA["image"] = ""
  715. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  716. def _render(self, surface):
  717. # Call the on_render() method, if any
  718. Node2D._callOnRender(self, surface)
  719. # Paint the sprite onto the surface
  720. if self._NODESPRITE_DATA["surface"] is not None:
  721. rect = self._NODESPRITE_DATA["rect"]
  722. scale = self._NODESPRITE_DATA["scale"]
  723. surf = self._NODESPRITE_DATA["surface"]()
  724. # Of course, only bother if we have a surface to work with.
  725. if surf is not None:
  726. # Do some prescaling work, if needed.
  727. if self._NODESPRITE_DATA["scale_dirty"]:
  728. self._NODESPRITE_DATA["scale_dirty"] = False
  729. self._NODESPRITE_UpdateFrameSurface(surf)
  730. self._NODESPRITE_UpdateScaleSurface(scale, surf)
  731. fsurf = surf # Initial assumption that the surface is also the "frame"
  732. # If we have a "frame" surface, however, let's get it and blit the rect into the frame surface.
  733. if "frame_surf" in self._NODESPRITE_DATA:
  734. fsurf = self._NODESPRITE_DATA["frame_surf"]
  735. fsurf.blit(surf, (0, 0), rect)
  736. # If scaling, then transform (scale) the frame surface into the scale surface and set the frame surface to the scale surface.
  737. if "scale_surf" in self._NODESPRITE_DATA:
  738. ssurf = self._NODESPRITE_DATA["scale_surf"]
  739. pygame.transform.scale(fsurf, ssurf.get_size(), ssurf)
  740. fsurf = ssurf
  741. # Place the sprite! WHEEEEE!
  742. pos = self.position
  743. surface.blit(fsurf, pos)
  744. # Call on all children
  745. Node._render(self, surface)
  746. def _NODESPRITE_UpdateFrameSurface(self, surf):
  747. rect = self.rect
  748. ssize = surf.get_size()
  749. if rect[2] == ssize[0] and rect[3] == ssize[1]:
  750. if "frame_surf" in self._NODESPRITE_DATA:
  751. del self._NODESPRITE_DATA
  752. return
  753. if "frame_surf" not in self._NODESPRITE_DATA:
  754. self._NODESPRITE_DATA["frame_surf"] = pygame.Surface((rect[2], rect[3]), pygame.SRCALPHA, surf)
  755. else:
  756. fsurf = self._NODESPRITE_DATA["frame_surf"]
  757. fsize = fsurf.get_size()
  758. if fsize[0] != rect[2] or fsize[1] != rect[3]:
  759. self._NODESPRITE_DATA["frame_surf"] = pygame.Surface((rect[2], rect[3]), pygame.SRCALPHA, surf)
  760. def _NODESPRITE_UpdateScaleSurface(self, scale, surf):
  761. ssurf = None
  762. if "scale_surf" in self._NODESPRITE_DATA:
  763. ssurf = self._NODESPRITE_DATA["scale_surf"]
  764. if scale[0] == 1.0 and scale[1] == 1.0:
  765. if ssurf is not None:
  766. del self._NODESPRITE_DATA["scale_surf"]
  767. return
  768. nw = int(self.rect_width * scale[0])
  769. nh = int(self.rect_height * scale[1])
  770. if nw != ssurf.get_width() or nh != ssurf.get_height():
  771. ssurf = pygame.Surface((nw, nh), pygame.SRCALPHA, surf)
  772. ssurf.fill(pygame.Color(0,0,0,0))
  773. self._NODESPRITE_DATA["scale_surf"] = ssurf
  774. def _NODESPRITE_ValidateRect(self):
  775. if self._NODESPRITE_DATA["surface"] is None:
  776. self._NODESPRITE_DATA["rect"] = [0,0,0,0]
  777. else:
  778. rect = self._NODESPRITE_DATA["rect"]
  779. isize = (self.image_width, self.image_height)
  780. if rect[0] < 0:
  781. rect[2] += rect[0]
  782. rect[0] = 0
  783. elif rect[0] >= isize[0]:
  784. rect[0] = isize[0]-1
  785. rect[2] = 0
  786. if rect[1] < 0:
  787. rect[3] += rect[1]
  788. rect[1] = 0
  789. elif rect[1] >= isize[1]:
  790. rect[1] = isize[1]-1
  791. rect[3] = 0
  792. if rect[2] < 0:
  793. rect[2] = 0
  794. elif rect[0] + rect[2] > isize[0]:
  795. rect[2] = isize[0] - rect[0]
  796. if rect[3] < 0:
  797. rect[3] = 0
  798. elif rect[1] + rect[3] > isize[1]:
  799. rect[3] = isize[1] - rect[1]
  800. self._NODESPRITE_DATA["scale_dirty"] = True