Python script to generate simple "dungeon maps"
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import random, sys, os
  2. from PIL import Image
  3. class CellMap:
  4. initial = []
  5. genmap = []
  6. def __init__(self, height=None, width=None, seed=None, death=None,
  7. birth=None, reps=0, out=None, color=None, chunky=None,
  8. treasure=None):
  9. self.height = height if height != None else 0
  10. self.width = width if width != None else 0
  11. self.seed = seed if seed != None else 0
  12. self.death = death if death != None else 0
  13. self.birth = birth if birth != None else 0
  14. self.reps = reps if reps != None else 0
  15. self.out = out if out != None else False
  16. self.color = color if color != None else False
  17. self.chunky = chunky if chunky != None else False
  18. self.treasure = treasure if treasure != None else False
  19. self.id = filename()
  20. @property
  21. def height(self):
  22. return self.__height
  23. @height.setter
  24. def height(self, height):
  25. self.__height = int(height) if int(height) > 0 else 0
  26. @property
  27. def width(self):
  28. return self.__width
  29. @width.setter
  30. def width(self, width):
  31. self.__width = int(width) if int(width) > 0 else 0
  32. @property
  33. def seed(self):
  34. return self.__seed
  35. @ seed.setter
  36. def seed(self, seed):
  37. self.__seed = int(seed) if int(seed) > 0 else 0
  38. @property
  39. def death(self):
  40. return self.__death
  41. @death.setter
  42. def death(self, death):
  43. self.__death = int(death) if int(death) > 0 else 0
  44. @property
  45. def birth(self):
  46. return self.__birth
  47. @birth.setter
  48. def birth(self, birth):
  49. self.__birth = int(birth) if int(birth) > 0 else 0
  50. @property
  51. def reps(self):
  52. return self.__reps
  53. @reps.setter
  54. def reps(self, reps):
  55. self.__reps = int(reps) if int(reps) > 0 else 0
  56. @property
  57. def out(self):
  58. return self.__out
  59. @out.setter
  60. def out(self, out):
  61. self.__out = bool(out)
  62. @property
  63. def color(self):
  64. return self.__color
  65. @color.setter
  66. def color(self, color):
  67. self.__color = bool(color)
  68. @property
  69. def chunky(self):
  70. return self.__chunky
  71. @chunky.setter
  72. def chunky(self, chunky):
  73. self.__chunky = bool(chunky)
  74. @property
  75. def treasure(self):
  76. return self.__treasure
  77. @treasure.setter
  78. def treasure(self, treasure):
  79. self.__treasure = bool(treasure)
  80. def generateFullMap(self):
  81. """ Puts everything together.
  82. """
  83. self.createMap()
  84. for _ in range(self.reps):
  85. self.smoothMap()
  86. if self.out:
  87. self.createImage()
  88. else:
  89. self.printScreen()
  90. def createMap(self):
  91. """ Initializes an x by y grid.
  92. x is width, y is height
  93. seed is the chance that a given cell will be "live" and should be an integer between 1-99.
  94. If True is equivalent to "wall", then higher seeds make more walls.
  95. """
  96. if self.__height == 0 or self.__width == 0 or self.__seed == 0:
  97. print("Height, width, and seed must be set before creating a map.")
  98. print("Current values: height: {}, width: {}, seed: {}".format(self.height, self.width, self.seed))
  99. return
  100. y = self.height
  101. x = self.width
  102. seed = self.seed
  103. new_map = []
  104. for j in range(y):
  105. new_row = []
  106. for i in range(x):
  107. new_row.append(True if random.randint(1,99) <= seed else False)
  108. new_map.append(new_row)
  109. self.initial = new_map
  110. self.genmap = self.initial
  111. def smoothMap(self):
  112. """ Refines the grid.
  113. """
  114. if self.death == 0 or self.birth == 0:
  115. print("The 'death' limit is currently {} and the 'birth' limit is {}.".format(self.death,self.birth))
  116. print("Smoothing with the 'death' or 'birth' limit set to 0 is not recommended.")
  117. print("Do you want to proceed? (y/N) ", end="")
  118. cont = input().strip()
  119. if cont.lower() != "y":
  120. print("Aborting.")
  121. return
  122. d_lmt = self.death
  123. a_lmt = self.birth
  124. new_map = []
  125. for j in range(len(self.genmap)):
  126. new_line = []
  127. for i in range(len(self.genmap[j])):
  128. x, y = i, j
  129. n_count = self.countWalls(x, y)
  130. if self.genmap[y][x]:
  131. # It's a wall.
  132. if n_count < d_lmt:
  133. # It has too few wall neighbors, so kill it.
  134. new_line.append(False)
  135. else:
  136. # It has enough wall neighbors, so keep it.
  137. new_line.append(True)
  138. else:
  139. # It's a path.
  140. if n_count > a_lmt:
  141. # It has too many wall neighbors, so it becomes a wall.
  142. new_line.append(True)
  143. else:
  144. # It's not too crowded, so it stays a path.
  145. new_line.append(False)
  146. new_map.append(new_line)
  147. self.genmap = new_map
  148. def countWalls(self, x, y):
  149. count = 0
  150. for j in range(-1,2):
  151. for i in range(-1,2):
  152. n_x, n_y = x+i, y+j
  153. if i == 0 and j == 0:
  154. continue
  155. if n_x < 0 or n_x >= len(self.genmap[j]) or n_y == 0 or n_y >= len(self.genmap):
  156. # The target cell is at the edge of the map and this neighbor is off the edge.
  157. # So we make this neighbor count as a wall.
  158. count += 1
  159. #pass
  160. elif self.genmap[n_y][n_x]:
  161. # This neighbor is on the map and is a wall.
  162. count += 1
  163. return count
  164. def printScreen(self):
  165. wall = "II"
  166. path = " "
  167. for line in self.genmap:
  168. print("".join([wall if x else path for x in line]))
  169. print()
  170. def createImage(self):
  171. x, y = len(self.genmap[0]), len(self.genmap)
  172. if self.chunky:
  173. true_x, true_y = x*2, y*2
  174. else:
  175. true_x, true_y = x, y
  176. img = Image.new("RGB",(true_x,true_y),(0,0,0))
  177. lst = []
  178. # Walls are black by default
  179. c_wall = [random.randint(0,255), random.randint(0,255), random.randint(0,255)] if self.color else [0,0,0]
  180. # Paths are white by default
  181. c_space = [255-x for x in c_wall]
  182. if self.chunky:
  183. for line in self.genmap:
  184. for _ in range(2):
  185. for val in line:
  186. for _ in range(2):
  187. lst.append(tuple(c_wall) if val else tuple(c_space))
  188. else:
  189. for line in self.genmap:
  190. for val in line:
  191. lst.append(tuple(c_wall) if val else tuple(c_space))
  192. img.putdata(lst)
  193. if not os.path.exists("maps"):
  194. os.makedirs("maps")
  195. fn = self.id
  196. i = 0
  197. while os.path.exists("maps/{}.png".format(fn)):
  198. i += 1
  199. fn = self.id + "-" + str(i)
  200. img.save('maps/{}.png'.format(fn))
  201. print("Saved maps/{}.png".format(fn))
  202. def filename():
  203. hexes = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
  204. fn = []
  205. for _ in range(16):
  206. fn.append(random.choice(hexes))
  207. return "".join(fn)
  208. def parseArgs(args):
  209. flags = {
  210. "--height" : 20,
  211. "--width" : 20,
  212. "--seed" : 45,
  213. "--death" : 4,
  214. "--birth" : 4,
  215. "--reps" : 2,
  216. "--out" : False,
  217. "--color" : False,
  218. "--chunky" : False,
  219. "--treas" : False,
  220. }
  221. for flag, default in flags.items():
  222. if flag in args:
  223. if flag == "--out":
  224. flags["--out"] = True
  225. elif flag == "--color":
  226. flags["--color"] = True
  227. elif flag == "--chunky":
  228. flags["--chunky"] = True
  229. else:
  230. flags[flag] = args[args.index(flag) + 1]
  231. return flags
  232. def main(args):
  233. flags = parseArgs(args)
  234. my_map = CellMap(flags["--height"],flags["--width"],flags["--seed"],flags["--death"],
  235. flags["--birth"],flags["--reps"],flags["--out"],flags["--color"],
  236. flags["--chunky"],flags["--treas"],)
  237. my_map.generateFullMap()
  238. if __name__ == "__main__":
  239. main(sys.argv)