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.

903 lines
30KB

  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._scale = (1.0, 1.0)
  277. self._scaleToDisplay = False
  278. self._scaleDirty = False
  279. self._keepAspectRatio = False
  280. self._alignCenter = False
  281. self._surface = None
  282. self._tsurface = None
  283. self.set_surface()
  284. def _updateTransformSurface(self):
  285. if self._surface is None:
  286. return
  287. self._scaleDirty = False
  288. if self._scaleToDisplay:
  289. dsize = Display.resolution
  290. ssize = self._surface.get_size()
  291. self._scale = (dsize[0] / ssize[0], dsize[1] / ssize[1])
  292. if self._keepAspectRatio:
  293. if self._scale[0] < self._scale[1]:
  294. self._scale = (self._scale[0], self._scale[0])
  295. else:
  296. self._scale = (self._scale[1], self._scale[1])
  297. if self._scale[0] == 1.0 and self._scale[1] == 1.0:
  298. self._tsurface = None
  299. return
  300. size = self._surface.get_size()
  301. nw = size[0] * self._scale[0]
  302. nh = 0
  303. if self._keepAspectRatio:
  304. nh = size[1] * self._scale[0]
  305. else:
  306. nh = size[1] * self._scale[1]
  307. self._tsurface = pygame.Surface((nw, nh), pygame.SRCALPHA, self._surface)
  308. self._tsurface.fill(pygame.Color(0,0,0,0))
  309. @property
  310. def resolution(self):
  311. if self._surface is None:
  312. return super().resolution
  313. return self._surface.get_size()
  314. @resolution.setter
  315. def resolution(self, res):
  316. try:
  317. self.set_surface(res)
  318. except (TypeError, ValueError) as e:
  319. raise e
  320. @property
  321. def width(self):
  322. return self.resolution[0]
  323. @property
  324. def height(self):
  325. return self.resolution[1]
  326. @property
  327. def scale(self):
  328. return self._scale
  329. @scale.setter
  330. def scale(self, scale):
  331. if self._keepAspectRatio:
  332. if not isinstance(scale, (int, float)):
  333. raise TypeError("Expected number value.")
  334. self._scale = (scale, self._scale[1])
  335. else:
  336. if not isinstance(scale, tuple):
  337. raise TypeError("Expected a tuple")
  338. if len(scale) != 2:
  339. raise ValueError("Expected tuple of length two.")
  340. if not isinstance(scale[0], (int, float)) or not isinstance(scale[1], (int, float)):
  341. raise TypeError("Expected number values.")
  342. self._scale = scale
  343. self._updateTransformSurface()
  344. @property
  345. def keep_aspect_ratio(self):
  346. return self._keepAspectRatio
  347. @keep_aspect_ratio.setter
  348. def keep_aspect_ratio(self, keep):
  349. self._keepAspectRatio = (keep == True)
  350. self._updateTransformSurface()
  351. @property
  352. def align_center(self):
  353. return self._alignCenter
  354. @align_center.setter
  355. def align_center(self, center):
  356. self._alignCenter = (center == True)
  357. @property
  358. def scale_to_display(self):
  359. return self._scaleToDisplay
  360. @scale_to_display.setter
  361. def scale_to_display(self, todisplay):
  362. if todisplay == True:
  363. self._scaleToDisplay = True
  364. Events.listen("VIDEORESIZE", self._OnVideoResize)
  365. else:
  366. self._scaleToDisplay = False
  367. Events.unlisten("VIDEORESIZE", self._OnVideoResize)
  368. self._updateTransformSurface()
  369. def scale_to(self, target_resolution):
  370. if self._surface is not None:
  371. size = self._surface.get_size()
  372. nscale = (float(size[0]) / float(target_resolution[0]), float(size[1]) / float(target_resolution[1]))
  373. self.scale = nscale
  374. def set_surface(self, resolution=None):
  375. dsurf = Display.surface
  376. if resolution is None:
  377. if dsurf is not None:
  378. self._surface = dsurf.convert_alpha()
  379. self._surface.fill(pygame.Color(0,0,0,0))
  380. self._updateTransformSurface()
  381. else:
  382. if not isinstance(resolution, tuple):
  383. raise TypeError("Expected a tuple.")
  384. if len(resolution) != 2:
  385. raise ValueError("Expected a tuple of length two.")
  386. if not isinstance(resolution[0], int) or not isinstance(resolution[1], int):
  387. raise TypeError("Tuple expected to contain integers.")
  388. if dsurf is not None:
  389. self._surface = pygame.Surface(resolution, pygame.SRCALPHA, dsurf)
  390. else:
  391. self._surface = pygame.Surface(resolution, pygame.SRCALPHA)
  392. self._surface.fill(pygame.Color(0,0,0,0))
  393. self._updateTransformSurface()
  394. def _render(self, surface):
  395. if self._surface is None:
  396. self.set_surface()
  397. if self._surface is not None:
  398. if self._scaleDirty:
  399. self._updateTransformSurface()
  400. Node2D._render(self, self._surface)
  401. else:
  402. Node2D._render(self, surface)
  403. self._scale_and_blit(surface)
  404. def _scale_and_blit(self, dest):
  405. dsize = dest.get_size()
  406. src = self._surface
  407. if self._tsurface is not None:
  408. pygame.transform.scale(self._surface, self._tsurface.get_size(), self._tsurface)
  409. src = self._tsurface
  410. ssize = src.get_size()
  411. posx = self.position_x
  412. posy = self.position_y
  413. if self._alignCenter:
  414. if dsize[0] > ssize[0]:
  415. posx += (dsize[0] - ssize[0]) * 0.5
  416. if dsize[1] > ssize[1]:
  417. posy += (dsize[1] - ssize[1]) * 0.5
  418. pos = (int(posx), int(posy))
  419. dest.blit(src, pos)
  420. def _OnVideoResize(self, event, data):
  421. if self._scaleToDisplay:
  422. self._scaleDirty = True
  423. class NodeText(Node2D):
  424. def __init__(self, name="NodeText", parent=None):
  425. try:
  426. Node2D.__init__(self, name, parent)
  427. except NodeError as e:
  428. raise e
  429. self._NODETEXT_DATA={
  430. "font_src":"",
  431. "size":26,
  432. "antialias":True,
  433. "color":pygame.Color(255,255,255),
  434. "background":None,
  435. "text":"Some Text",
  436. "surface":None
  437. }
  438. @property
  439. def font_src(self):
  440. return self._NODETEXT_DATA["font_src"]
  441. @font_src.setter
  442. def font_src(self, src):
  443. res = self.resource
  444. if src != "" and src != self._NODETEXT_DATA["font_src"] and res.is_valid("font", src):
  445. self._NODETEXT_DATA["font_src"] = src
  446. if not res.has("font", src):
  447. res.store("font", src)
  448. self._NODETEXT_DATA["surface"] = None
  449. @property
  450. def size(self):
  451. return self._NODETEXT_DATA["size"]
  452. @size.setter
  453. def size(self, size):
  454. if not isinstance(size, int):
  455. raise TypeError("Expected integer value.")
  456. if size <= 0:
  457. raise ValueError("Size must be greater than zero.")
  458. if size != self._NODETEXT_DATA["size"]:
  459. self._NODETEXT_DATA["size"] = size
  460. self._NODETEXT_DATA["surface"] = None
  461. @property
  462. def antialias(self):
  463. return self._NODETEXT_DATA["antialias"]
  464. @antialias.setter
  465. def antialias(self, enable):
  466. enable = (enable == True)
  467. if enable != self._NODETEXT_DATA["antialias"]:
  468. self._NODETEXT_DATA["antialias"] = enable
  469. self._NODETEXT_DATA["surface"] = None
  470. @property
  471. def text(self):
  472. return self._NODETEXT_DATA["text"]
  473. @text.setter
  474. def text(self, text):
  475. if text != self._NODETEXT_DATA["text"]:
  476. self._NODETEXT_DATA["text"] = text
  477. self._NODETEXT_DATA["surface"] = None
  478. def _setColor(self, cname, r, g, b, a):
  479. if r < 0 or r > 255:
  480. raise ValueError("Red value out of bounds.")
  481. if g < 0 or g > 255:
  482. raise ValueError("Green value out of bounds.")
  483. if b < 0 or b > 255:
  484. raise ValueError("Blue value out of bounds.")
  485. if a < 0 or a > 255:
  486. raise ValueError("Alpha value out of bounds.")
  487. color = self._NODETEXT_DATA[cname]
  488. if color.r != r or color.g != g or color.b != b or color.a != a:
  489. self._NODETEXT_DATA[cname] = pygame.Color(r,g,b,a)
  490. self._NODETEXT_DATA["surface"] = None
  491. def _getColor(self, cname):
  492. if self._NODETEXT_DATA[cname] is None:
  493. return (0,0,0,0)
  494. else:
  495. c = self._NODETEXT_DATA[cname]
  496. return (c.r, c.g, c.b, c.a)
  497. def set_color(self, r, g, b, a=255):
  498. try:
  499. self._setColor("color", r, g, b, a)
  500. except ValueError as e:
  501. raise e
  502. return self
  503. def get_color(self):
  504. return self._getColor("color")
  505. def set_background(self, r, g, b, a=255):
  506. try:
  507. self._setColor("background", r, g, b, a)
  508. except ValueError as e:
  509. raise e
  510. return self
  511. def clear_background(self):
  512. if self._NODETEXT_DATA["background"] is not None:
  513. self._NODETEXT_DATA["background"] = None
  514. self._NODETEXT_DATA["surface"] = None
  515. return self
  516. def get_background(self):
  517. c = self._getColor("background")
  518. if c[3] <= 0:
  519. return None
  520. return c
  521. def _render(self, surface):
  522. if self._NODETEXT_DATA["surface"] is None and self._NODETEXT_DATA["text"] != "":
  523. res = self.resource
  524. fnt = res.get("font", self._NODETEXT_DATA["font_src"], {"size":self._NODETEXT_DATA["size"]})
  525. if fnt is not None and fnt() is not None:
  526. surf = None
  527. try:
  528. text = self.text
  529. antialias = self.antialias
  530. color = self._NODETEXT_DATA["color"]
  531. background = self._NODETEXT_DATA["background"]
  532. surf = fnt().render(text, antialias, color, background)
  533. except pygame.error as e:
  534. pass # TODO: Update to send out warning!
  535. self._NODETEXT_DATA["surface"] = surf
  536. # We really don't want to keep the font instance around... just in case we want to use the same font at different sizes.
  537. res.clear("font", self._NODETEXT_DATA["font_src"])
  538. Node2D._render(self, surface)
  539. if self._NODETEXT_DATA["surface"] is not None:
  540. pos = self.position
  541. pos = (int(pos[0]), int(pos[1]))
  542. surface.blit(self._NODETEXT_DATA["surface"], pos)
  543. class NodeSprite(Node2D):
  544. def __init__(self, name="NodeSprite", parent=None):
  545. try:
  546. Node2D.__init__(self, name, parent)
  547. except NodeError as e:
  548. raise e
  549. self._NODESPRITE_DATA={
  550. "rect":[0,0,0,0],
  551. "image":"",
  552. "scale":[1.0, 1.0],
  553. "scale_dirty":True,
  554. "surface":None
  555. }
  556. @property
  557. def image_width(self):
  558. if self._NODESPRITE_DATA["surface"] is None:
  559. return 0
  560. surf = self._NODESPRITE_DATA["surface"]()
  561. return surf.get_width()
  562. @property
  563. def image_height(self):
  564. if self._NODESPRITE_DATA["surface"] is None:
  565. return 0
  566. surf = self._NODESPRITE_DATA["surface"]()
  567. return surf.get_height()
  568. @property
  569. def sprite_width(self):
  570. return int(self.rect_width * self.scale_x)
  571. @property
  572. def sprite_height(self):
  573. return int(self.rect_height * self.scale_y)
  574. @property
  575. def rect(self):
  576. return (self._NODESPRITE_DATA["rect"][0],
  577. self._NODESPRITE_DATA["rect"][1],
  578. self._NODESPRITE_DATA["rect"][2],
  579. self._NODESPRITE_DATA["rect"][3])
  580. @rect.setter
  581. def rect(self, rect):
  582. if not isinstance(rect, (list, tuple)):
  583. raise TypeError("Expected a list or tuple.")
  584. if len(rect) != 4:
  585. raise ValueError("rect value contains wrong number of values.")
  586. try:
  587. self.rect_x = rect[0]
  588. self.rect_y = rect[1]
  589. self.rect_width = rect[2]
  590. self.rect_height = rect[3]
  591. except Exception as e:
  592. raise e
  593. @property
  594. def rect_x(self):
  595. return self._NODESPRITE_DATA["rect"][0]
  596. @rect_x.setter
  597. def rect_x(self, v):
  598. if not isinstance(v, int):
  599. raise TypeError("Expected integer value.")
  600. self._NODESPRITE_DATA["rect"][0] = v
  601. self._NODESPRITE_ValidateRect()
  602. @property
  603. def rect_y(self):
  604. return self._NODESPRITE_DATA["rect"][1]
  605. @rect_y.setter
  606. def rect_y(self, v):
  607. if not isinstance(v, int):
  608. raise TypeError("Expected integer value.")
  609. self._NODESPRITE_DATA["rect"][1] = v
  610. self._NODESPRITE_ValidateRect()
  611. @property
  612. def rect_width(self):
  613. return self._NODESPRITE_DATA["rect"][2]
  614. @rect_width.setter
  615. def rect_width(self, v):
  616. if not isinstance(v, int):
  617. raise TypeError("Expected integer value.")
  618. self._NODESPRITE_DATA["rect"][2] = v
  619. self._NODESPRITE_ValidateRect()
  620. @property
  621. def rect_height(self):
  622. return self._NODESPRITE_DATA["rect"][3]
  623. @rect_height.setter
  624. def rect_height(self, v):
  625. if not isinstance(v, int):
  626. raise TypeError("Expected integer value.")
  627. self._NODESPRITE_DATA["rect"][3] = v
  628. self._NODESPRITE_ValidateRect()
  629. @property
  630. def center(self):
  631. r = self._NODESPRITE_DATA["rect"]
  632. return (int(r[0] + (r[2] * 0.5)), int(r[1] + (r[3] * 0.5)))
  633. @property
  634. def scale(self):
  635. return (self._NODESPRITE_DATA["scale"][0], self._NODESPRITE_DATA["scale"][1])
  636. @scale.setter
  637. def scale(self, scale):
  638. if not isinstance(scale, (list, tuple)):
  639. raise TypeError("Expected a list or tuple.")
  640. if len(scale) != 2:
  641. raise ValueError("Scale contains wrong number of values.")
  642. try:
  643. self.scale_x = scale[0]
  644. self.scale_y = scale[1]
  645. except Exception as e:
  646. raise e
  647. @property
  648. def scale_x(self):
  649. return self._NODESPRITE_DATA["scale"][0]
  650. @scale_x.setter
  651. def scale_x(self, v):
  652. if not isinstance(v, (int, float)):
  653. raise TypeError("Expected number value.")
  654. self._NODESPRITE_DATA["scale"][0] = float(v)
  655. self._NODESPRITE_DATA["scale_dirty"] = True
  656. @property
  657. def scale_y(self):
  658. return self._NODESPRITE_DATA["scale"][1]
  659. @scale_y.setter
  660. def scale_y(self, v):
  661. if not isinstance(v, (int, float)):
  662. raise TypeError("Expected number value.")
  663. self._NODESPRITE_DATA["scale"][1] = float(v)
  664. self._NODESPRITE_DATA["scale_dirty"] = True
  665. @property
  666. def image(self):
  667. return self._NODESPRITE_DATA["image"]
  668. @image.setter
  669. def image(self, src):
  670. src = src.strip()
  671. if self._NODESPRITE_DATA["image"] == src:
  672. return # Nothing to change... lol
  673. if self._NODESPRITE_DATA["image"] != "":
  674. self._NODESPRITE_DATA["surface"] = None # Clear reference to original surface.
  675. if src != "":
  676. rm = self.resource
  677. try:
  678. if not rm.has("graphic", src):
  679. rm.store("graphic", src)
  680. self._NODESPRITE_DATA["image"] = src
  681. self._NODESPRITE_DATA["surface"] = rm.get("graphic", src)
  682. if self._NODESPRITE_DATA["surface"] is None:
  683. self._NODESPRITE_DATA["image"] = ""
  684. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  685. else:
  686. # Resetting the rect to identity for the new image.
  687. surf = self._NODESPRITE_DATA["surface"]()
  688. size = surf.get_size()
  689. self._NODESPRITE_DATA["rect"]=[0,0,size[0], size[1]]
  690. except Exception as e:
  691. raise e
  692. else:
  693. self._NODESPRITE_DATA["image"] = ""
  694. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  695. def _render(self, surface):
  696. # Call the on_render() method, if any
  697. Node2D._callOnRender(self, surface)
  698. # Paint the sprite onto the surface
  699. if self._NODESPRITE_DATA["surface"] is not None:
  700. rect = self._NODESPRITE_DATA["rect"]
  701. scale = self._NODESPRITE_DATA["scale"]
  702. surf = self._NODESPRITE_DATA["surface"]()
  703. # Of course, only bother if we have a surface to work with.
  704. if surf is not None:
  705. # Do some prescaling work, if needed.
  706. if self._NODESPRITE_DATA["scale_dirty"]:
  707. self._NODESPRITE_DATA["scale_dirty"] = False
  708. self._NODESPRITE_UpdateFrameSurface(surf)
  709. self._NODESPRITE_UpdateScaleSurface(scale, surf)
  710. fsurf = surf # Initial assumption that the surface is also the "frame"
  711. # If we have a "frame" surface, however, let's get it and blit the rect into the frame surface.
  712. if "frame_surf" in self._NODESPRITE_DATA:
  713. fsurf = self._NODESPRITE_DATA["frame_surf"]
  714. fsurf.blit(surf, (0, 0), rect)
  715. # If scaling, then transform (scale) the frame surface into the scale surface and set the frame surface to the scale surface.
  716. if "scale_surf" in self._NODESPRITE_DATA:
  717. ssurf = self._NODESPRITE_DATA["scale_surf"]
  718. pygame.transform.scale(fsurf, ssurf.get_size(), ssurf)
  719. fsurf = ssurf
  720. # Place the sprite! WHEEEEE!
  721. pos = self.position
  722. surface.blit(fsurf, pos)
  723. # Call on all children
  724. Node._render(self, surface)
  725. def _NODESPRITE_UpdateFrameSurface(self, surf):
  726. rect = self.rect
  727. ssize = surf.get_size()
  728. if rect[2] == ssize[0] and rect[3] == ssize[1]:
  729. if "frame_surf" in self._NODESPRITE_DATA:
  730. del self._NODESPRITE_DATA
  731. return
  732. if "frame_surf" not in self._NODESPRITE_DATA:
  733. self._NODESPRITE_DATA["frame_surf"] = pygame.Surface((rect[2], rect[3]), pygame.SRCALPHA, surf)
  734. else:
  735. fsurf = self._NODESPRITE_DATA["frame_surf"]
  736. fsize = fsurf.get_size()
  737. if fsize[0] != rect[2] or fsize[1] != rect[3]:
  738. self._NODESPRITE_DATA["frame_surf"] = pygame.Surface((rect[2], rect[3]), pygame.SRCALPHA, surf)
  739. def _NODESPRITE_UpdateScaleSurface(self, scale, surf):
  740. ssurf = None
  741. if "scale_surf" in self._NODESPRITE_DATA:
  742. ssurf = self._NODESPRITE_DATA["scale_surf"]
  743. if scale[0] == 1.0 and scale[1] == 1.0:
  744. if ssurf is not None:
  745. del self._NODESPRITE_DATA["scale_surf"]
  746. return
  747. nw = int(self.rect_width * scale[0])
  748. nh = int(self.rect_height * scale[1])
  749. if nw != ssurf.get_width() or nh != ssurf.get_height():
  750. ssurf = pygame.Surface((nw, nh), pygame.SRCALPHA, surf)
  751. ssurf.fill(pygame.Color(0,0,0,0))
  752. self._NODESPRITE_DATA["scale_surf"] = ssurf
  753. def _NODESPRITE_ValidateRect(self):
  754. if self._NODESPRITE_DATA["surface"] is None:
  755. self._NODESPRITE_DATA["rect"] = [0,0,0,0]
  756. else:
  757. rect = self._NODESPRITE_DATA["rect"]
  758. isize = (self.image_width, self.image_height)
  759. if rect[0] < 0:
  760. rect[2] += rect[0]
  761. rect[0] = 0
  762. elif rect[0] >= isize[0]:
  763. rect[0] = isize[0]-1
  764. rect[2] = 0
  765. if rect[1] < 0:
  766. rect[3] += rect[1]
  767. rect[1] = 0
  768. elif rect[1] >= isize[1]:
  769. rect[1] = isize[1]-1
  770. rect[3] = 0
  771. if rect[2] < 0:
  772. rect[2] = 0
  773. elif rect[0] + rect[2] > isize[0]:
  774. rect[2] = isize[0] - rect[0]
  775. if rect[3] < 0:
  776. rect[3] = 0
  777. elif rect[1] + rect[3] > isize[1]:
  778. rect[3] = isize[1] - rect[1]
  779. self._NODESPRITE_DATA["scale_dirty"] = True