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.

706 lines
23KB

  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(this._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"][0] = float(v)
  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"][1] = 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(value, 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 _update(self, dt):
  165. if hasattr(self, "on_update"):
  166. self.on_update(dt)
  167. for c in self._NODE_DATA["children"]:
  168. c._update(dt)
  169. def _render(self, surface):
  170. for c in self._NODE_DATA["children"]:
  171. c._render(surface)
  172. class Node2D(Node):
  173. def __init__(self, name="Node2D", parent=None):
  174. try:
  175. Node.__init__(self, name, parent)
  176. except NodeError as e:
  177. raise e
  178. def _callOnRender(self, surface):
  179. if hasattr(self, "on_render"):
  180. self._ACTIVE_SURF = surface
  181. self.on_render()
  182. del self._ACTIVE_SURF
  183. def _render(self, surface):
  184. self._callOnRender(surface)
  185. Node._render(self, surface)
  186. def draw_image(self, img, pos=(0,0), rect=None):
  187. if not hasattr(self, "_ACTIVE_SURF"):
  188. return
  189. self._ACTIVE_SURF.blit(img, pos, rect)
  190. def fill(self, color):
  191. if not hasattr(self, "_ACTIVE_SURF"):
  192. return
  193. self._ACTIVE_SURF.fill(color)
  194. def draw_lines(self, points, color, thickness=1, closed=False):
  195. if not hasattr(self, "_ACTIVE_SURF"):
  196. return
  197. pygame.draw.lines(self._ACTIVE_SURF, color, closed, points, thickness)
  198. def draw_rect(self, rect, color, thickness=1):
  199. if not hasattr(self, "_ACTIVE_SURF"):
  200. return
  201. pygame.draw.rect(self._ACTIVE_SURF, color, rect, thickness)
  202. def draw_ellipse(self, rect, color, thickness=1, fill_color=None):
  203. if not hasattr(self, "_ACTIVE_SURF"):
  204. return
  205. if fill_color is not None:
  206. pygame.draw.ellipse(self._ACTIVE_SURF, fill_color, rect)
  207. if thickness > 0:
  208. pygame.draw.ellipse(self._ACTIVE_SURF, color, rect, thickness)
  209. def draw_circle(self, pos, radius, color, thickness=1, fill_color=None):
  210. if not hasattr(self, "_ACTIVE_SURF"):
  211. return
  212. if fill_color is not None:
  213. pygame.draw.circle(self._ACTIVE_SURF, fill_color, pos, radius)
  214. if thickness > 0:
  215. pygame.draw.circle(self._ACTIVE_SURF, color, pos, radius, thickness)
  216. def draw_polygon(self, points, color, thickness=1, fill_color=None):
  217. if not hasattr(self, "_ACTIVE_SURF"):
  218. return
  219. if fill_color is not None:
  220. pygame.draw.polygon(self._ACTIVE_SURF, fill_color, points)
  221. if thickness >= 1:
  222. pygame.draw.polygon(self._ACTIVE_SURF, color, points, thickness)
  223. class NodeSurface(Node2D):
  224. def __init__(self, name="NodeSurface", parent=None):
  225. try:
  226. Node2D.__init__(self, name, parent)
  227. except NodeError as e:
  228. raise e
  229. # TODO: Update this class to use the _NODE*_DATA={} structure.
  230. self._scale = (1.0, 1.0)
  231. self._scaleToDisplay = False
  232. self._scaleDirty = False
  233. self._keepAspectRatio = False
  234. self._alignCenter = False
  235. self._surface = None
  236. self._tsurface = None
  237. self.set_surface()
  238. def _updateTransformSurface(self):
  239. if self._surface is None:
  240. return
  241. self._scaleDirty = False
  242. if self._scaleToDisplay:
  243. dsize = Display.resolution
  244. ssize = self._surface.get_size()
  245. self._scale = (dsize[0] / ssize[0], dsize[1] / ssize[1])
  246. if self._keepAspectRatio:
  247. if self._scale[0] < self._scale[1]:
  248. self._scale = (self._scale[0], self._scale[0])
  249. else:
  250. self._scale = (self._scale[1], self._scale[1])
  251. if self._scale[0] == 1.0 and self._scale[1] == 1.0:
  252. self._tsurface = None
  253. return
  254. size = self._surface.get_size()
  255. nw = size[0] * self._scale[0]
  256. nh = 0
  257. if self._keepAspectRatio:
  258. nh = size[1] * self._scale[0]
  259. else:
  260. nh = size[1] * self._scale[1]
  261. self._tsurface = pygame.Surface((nw, nh), pygame.SRCALPHA, self._surface)
  262. self._tsurface.fill(pygame.Color(0,0,0,0))
  263. @property
  264. def resolution(self):
  265. if self._surface is None:
  266. return (0,0)
  267. return self._surface.get_size()
  268. @resolution.setter
  269. def resolution(self, res):
  270. try:
  271. self.set_surface(res)
  272. except (TypeError, ValueError) as e:
  273. raise e
  274. @property
  275. def width(self):
  276. return self.resolution[0]
  277. @property
  278. def height(self):
  279. return self.resolution[1]
  280. @property
  281. def scale(self):
  282. return self._scale
  283. @scale.setter
  284. def scale(self, scale):
  285. if self._keepAspectRatio:
  286. if not isinstance(scale, (int, float)):
  287. raise TypeError("Expected number value.")
  288. self._scale = (scale, self._scale[1])
  289. else:
  290. if not isinstance(scale, tuple):
  291. raise TypeError("Expected a tuple")
  292. if len(scale) != 2:
  293. raise ValueError("Expected tuple of length two.")
  294. if not isinstance(scale[0], (int, float)) or not isinstance(scale[1], (int, float)):
  295. raise TypeError("Expected number values.")
  296. self._scale = scale
  297. self._updateTransformSurface()
  298. @property
  299. def keep_aspect_ratio(self):
  300. return self._keepAspectRatio
  301. @keep_aspect_ratio.setter
  302. def keep_aspect_ratio(self, keep):
  303. self._keepAspectRatio = (keep == True)
  304. self._updateTransformSurface()
  305. @property
  306. def align_center(self):
  307. return self._alignCenter
  308. @align_center.setter
  309. def align_center(self, center):
  310. self._alignCenter = (center == True)
  311. @property
  312. def scale_to_display(self):
  313. return self._scaleToDisplay
  314. @scale_to_display.setter
  315. def scale_to_display(self, todisplay):
  316. if todisplay == True:
  317. self._scaleToDisplay = True
  318. Events.listen("VIDEORESIZE", self._OnVideoResize)
  319. else:
  320. self._scaleToDisplay = False
  321. Events.unlisten("VIDEORESIZE", self._OnVideoResize)
  322. self._updateTransformSurface()
  323. def scale_to(self, target_resolution):
  324. if self._surface is not None:
  325. size = self._surface.get_size()
  326. nscale = (float(size[0]) / float(target_resolution[0]), float(size[1]) / float(target_resolution[1]))
  327. self.scale = nscale
  328. def set_surface(self, resolution=None):
  329. dsurf = Display.surface
  330. if resolution is None:
  331. if dsurf is not None:
  332. self._surface = dsurf.convert_alpha()
  333. self._surface.fill(pygame.Color(0,0,0,0))
  334. self._updateTransformSurface()
  335. else:
  336. if not isinstance(resolution, tuple):
  337. raise TypeError("Expected a tuple.")
  338. if len(resolution) != 2:
  339. raise ValueError("Expected a tuple of length two.")
  340. if not isinstance(resolution[0], int) or not isinstance(resolution[1], int):
  341. raise TypeError("Tuple expected to contain integers.")
  342. if dsurf is not None:
  343. self._surface = pygame.Surface(resolution, pygame.SRCALPHA, dsurf)
  344. else:
  345. self._surface = pygame.Surface(resolution, pygame.SRCALPHA)
  346. self._surface.fill(pygame.Color(0,0,0,0))
  347. self._updateTransformSurface()
  348. def _render(self, surface):
  349. if self._surface is None:
  350. self.set_surface()
  351. if self._surface is not None:
  352. if self._scaleDirty:
  353. self._updateTransformSurface()
  354. Node2D._render(self, self._surface)
  355. else:
  356. Node2D._render(self, surface)
  357. self._scale_and_blit(surface)
  358. def _scale_and_blit(self, dest):
  359. dsize = dest.get_size()
  360. src = self._surface
  361. if self._tsurface is not None:
  362. pygame.transform.scale(self._surface, self._tsurface.get_size(), self._tsurface)
  363. src = self._tsurface
  364. ssize = src.get_size()
  365. posx = self.position_x
  366. posy = self.position_y
  367. if self._alignCenter:
  368. if dsize[0] > ssize[0]:
  369. posx += (dsize[0] - ssize[0]) * 0.5
  370. if dsize[1] > ssize[1]:
  371. posy += (dsize[1] - ssize[1]) * 0.5
  372. pos = (int(posx), int(posy))
  373. dest.blit(src, pos)
  374. def _OnVideoResize(self, event, data):
  375. if self._scaleToDisplay:
  376. self._scaleDirty = True
  377. class NodeSprite(Node2D):
  378. def __init__(self, name="NodeSprite", parent=None):
  379. try:
  380. Node2D.__init__(self, name, parent)
  381. except NodeError as e:
  382. raise e
  383. self._NODESPRITE_DATA={
  384. "rect":[0,0,0,0],
  385. "image":"",
  386. "scale":[1.0, 1.0],
  387. "surface":None
  388. }
  389. @property
  390. def image_width(self):
  391. if self._NODESPRITE_DATA["surface"] is None:
  392. return 0
  393. surf = self._NODESPRITE_DATA["surface"]()
  394. return surf.get_width()
  395. @property
  396. def image_height(self):
  397. if self._NODESPRITE_DATA["surface"] is None:
  398. return 0
  399. surf = self._NODESPRITE_DATA["surface"]()
  400. return surf.get_height()
  401. @property
  402. def sprite_width(self):
  403. return int(self.rect_width * self.scale_x)
  404. @property
  405. def sprite_height(self):
  406. return int(self.rect_height * self.scale_y)
  407. @property
  408. def rect(self):
  409. return (self._NODESPRITE_DATA["rect"][0],
  410. self._NODESPRITE_DATA["rect"][1],
  411. self._NODESPRITE_DATA["rect"][2],
  412. self._NODESPRITE_DATA["rect"][3])
  413. @rect.setter
  414. def rect(self, rect):
  415. if not isinstance(rect, (list, tuple)):
  416. raise TypeError("Expected a list or tuple.")
  417. if len(rect) != 4:
  418. raise ValueError("rect value contains wrong number of values.")
  419. try:
  420. self.rect_x = rect[0]
  421. self.rect_y = rect[1]
  422. self.rect_width = rect[2]
  423. self.rect_height = rect[3]
  424. except Exception as e:
  425. raise e
  426. @property
  427. def rect_x(self):
  428. return self._NODESPRITE_DATA["rect"][0]
  429. @rect_x.setter
  430. def rect_x(self, v):
  431. if not isinstance(v, int):
  432. raise TypeError("Expected integer value.")
  433. self._NODESPRITE_DATA["rect"][0] = v
  434. self._NODESPRITE_ValidateRect()
  435. @property
  436. def rect_y(self):
  437. return self._NODESPRITE_DATA["rect"][1]
  438. @rect_y.setter
  439. def rect_y(self, v):
  440. if not isinstance(v, int):
  441. raise TypeError("Expected integer value.")
  442. self._NODESPRITE_DATA["rect"][1] = v
  443. self._NODESPRITE_ValidateRect()
  444. @property
  445. def rect_width(self):
  446. return self._NODESPRITE_DATA["rect"][2]
  447. @rect_width.setter
  448. def rect_width(self, v):
  449. if not isinstance(v, int):
  450. raise TypeError("Expected integer value.")
  451. self._NODESPRITE_DATA["rect"][2] = v
  452. self._NODESPRITE_ValidateRect()
  453. @property
  454. def rect_height(self):
  455. return self._NODESPRITE_DATA["rect"][3]
  456. @rect_height.setter
  457. def rect_height(self, v):
  458. if not isinstance(v, int):
  459. raise TypeError("Expected integer value.")
  460. self._NODESPRITE_DATA["rect"][3] = v
  461. self._NODESPRITE_ValidateRect()
  462. @property
  463. def center(self):
  464. r = self._NODESPRITE_DATA["rect"]
  465. return (int(r[0] + (r[2] * 0.5)), int(r[1] + (r[3] * 0.5)))
  466. @property
  467. def scale(self):
  468. return (self._NODESPRITE_DATA["scale"][0], self._NODESPRITE_DATA["scale"][1])
  469. @scale.setter
  470. def scale(self, scale):
  471. if not isinstance(scale, (list, tuple)):
  472. raise TypeError("Expected a list or tuple.")
  473. if len(scale) != 2:
  474. raise ValueError("Scale contains wrong number of values.")
  475. try:
  476. self.scale_x = scale[0]
  477. self.scale_y = scale[1]
  478. except Exception as e:
  479. raise e
  480. @property
  481. def scale_x(self):
  482. return self._NODESPRITE_DATA["scale"][0]
  483. @scale_x.setter
  484. def scale_x(self, v):
  485. if not isinstance(v, (int, float)):
  486. raise TypeError("Expected number value.")
  487. self._NODESPRITE_DATA["scale"][0] = float(v)
  488. self._NODESPRITE_DATA["scale_dirty"] = True
  489. @property
  490. def scale_y(self):
  491. return self._NODESPRITE_DATA["scale"][1]
  492. @scale_y.setter
  493. def scale_y(self, v):
  494. if not isinstance(v, (int, float)):
  495. raise TypeError("Expected number value.")
  496. self._NODESPRITE_DATA["scale"][1] = float(v)
  497. self._NODESPRITE_DATA["scale_dirty"] = True
  498. @property
  499. def image(self):
  500. return self._NODESPRITE_DATA["image"]
  501. @image.setter
  502. def image(self, src):
  503. src = src.strip()
  504. if self._NODESPRITE_DATA["image"] == src:
  505. return # Nothing to change... lol
  506. if self._NODESPRITE_DATA["image"] != "":
  507. self._NODESPRITE_DATA["surface"] = None # Clear reference to original surface.
  508. if src != "":
  509. rm = self.resource
  510. try:
  511. if not rm.has("graphic", src):
  512. rm.store("graphic", src)
  513. self._NODESPRITE_DATA["image"] = src
  514. self._NODESPRITE_DATA["surface"] = rm.get("graphic", src)
  515. if self._NODESPRITE_DATA["surface"] is None:
  516. self._NODESPRITE_DATA["image"] = ""
  517. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  518. else:
  519. # Resetting the rect to identity for the new image.
  520. surf = self._NODESPRITE_DATA["surface"]()
  521. size = surf.get_size()
  522. self._NODESPRITE_DATA["rect"]=[0,0,size[0], size[1]]
  523. except Exception as e:
  524. raise e
  525. else:
  526. self._NODESPRITE_DATA["image"] = ""
  527. self._NODESPRITE_DATA["rect"]=[0,0,0,0]
  528. def _render(self, surface):
  529. # Call the on_render() method, if any
  530. Node2D._callOnRender(self, surface)
  531. # Paint the sprite onto the surface
  532. if self._NODESPRITE_DATA["surface"] is not None:
  533. rect = self._NODESPRITE_DATA["rect"]
  534. scale = self._NODESPRITE_DATA["scale"]
  535. surf = self._NODESPRITE_DATA["surface"]()
  536. # Of course, only bother if we have a surface to work with.
  537. if surf is not None:
  538. # Do some prescaling work, if needed.
  539. if self._NODESPRITE_DATA["scale_dirty"]:
  540. self._NODESPRITE_UpdateScaleSurface(scale, surf)
  541. fsurf = surf # Initial assumption that the surface is also the "frame"
  542. # If we have a "frame" surface, however, let's get it and blit the rect into the frame surface.
  543. if "frame_surf" in self._NODESPRITE_DATA:
  544. fsurf = self._NODESPRITE_DATA["frame_surf"]
  545. fsurf.blit(surf, (0, 0), rect)
  546. # If scaling, then transform (scale) the frame surface into the scale surface and set the frame surface to the scale surface.
  547. if "scale_surf" in self._NODESPRITE_DATA:
  548. ssurf = self._NODESPRITE_DATA["scale_surf"]
  549. pygame.transform.scale(fsurf, ssurf.get_size(), ssurf)
  550. fsurf = ssurf
  551. # Place the sprite! WHEEEEE!
  552. pos = self.position
  553. surface.blit(fsurf, pos)
  554. # Call on all children
  555. Node._render(self, surface)
  556. def _NODESPRITE_UpdateScaleSurface(self, scale, surf):
  557. self._NODESPRITE_DATA["scale_dirty"] = False
  558. ssurf = None
  559. if "scale_surf" in self._NODESPRITE_DATA:
  560. ssurf = self._NODESPRITE_DATA["scale_surf"]
  561. if scale[0] == 1.0 and scale[1] == 1.0:
  562. if ssurf is not None:
  563. del self._NODESPRITE_DATA["scale_surf"]
  564. return
  565. nw = int(self.rect_width * scale[0])
  566. nh = int(self.rect_height * scale[1])
  567. if nw != ssurf.get_width() or nh != ssurf.get_height():
  568. ssurf = pygame.Surface((nw, nh), pygame.SRCALPHA, surf)
  569. ssurf.fill(pygame.Color(0,0,0,0))
  570. self._NODESPRITE_DATA["scale_surf"] = ssurf
  571. def _NODESPRITE_ValidateRect(self):
  572. if self._NODESPRITE_DATA["surface"] is None:
  573. self._NODESPRITE_DATA["rect"] = [0,0,0,0]
  574. else:
  575. rect = self._NODESPRITE_DATA["rect"]
  576. isize = (self.image_width, self.image_height)
  577. if rect[0] < 0:
  578. rect[2] += rect[0]
  579. rect[0] = 0
  580. elif rect[0] >= isize[0]:
  581. rect[0] = isize[0]-1
  582. rect[2] = 0
  583. if rect[1] < 0:
  584. rect[3] += rect[1]
  585. rect[1] = 0
  586. elif rect[1] >= isize[1]:
  587. rect[1] = isize[1]-1
  588. rect[3] = 0
  589. if rect[2] < 0:
  590. rect[2] = 0
  591. elif rect[0] + rect[2] > isize[0]:
  592. rect[2] = isize[0] - rect[0]
  593. if rect[3] < 0:
  594. rect[3] = 0
  595. elif rect[1] + rect[3] > isize[1]:
  596. rect[3] = isize[1] - rect[1]
  597. fssize = [0,0]
  598. if rect[2] > 0 and rect[3] > 0:
  599. if rect[2] < isize[0] or rect[1] < isize[1]:
  600. surf = self._NODESPRITE_DATA["surface"]()
  601. self._NODESPRITE_DATA["frame_surf"] = pygame.Surface((rect[2], rect[3]), pygame.SRCALPHA, surf)
  602. if fssize[0] > 0 and fssize[1] > 0:
  603. pass
  604. elif "frame_surf" in self._NODESPRITE_DATA:
  605. del self._NODESPRITE_DATA["frame_surf"]