这是我所做的:
#!/usr/bin/env python3
import math
import random
class Tree(object):
def __init__(self, height=24, width=80, branches=5):
self.height = height
self.width = width
self.branches = branches
def draw(self):
tree = [[" " for i in range(self.width)] for j in range(self.height)]
# These are arbitrary trunk dimensions, you can change them
trunk = {}
trunk["width"] = math.floor(self.width / 12)
trunk["height"] = math.floor(self.height * (2 / 3))
# Center the trunk. (0, 0) is the top-left corner of the screen.
trunk["x"] = int(math.floor(self.width / 2) - math.floor(trunk["width"] / 2))
trunk["y"] = int(self.height - trunk["height"])
for i in range(trunk["height"]):
for j in range(trunk["width"]):
tree[i + trunk["y"]][j + trunk["x"]] = "#"
# Add branches
for i in range(self.branches):
# Choose a position on the side of the trunk
branch = {}
if random.randint(0, 1):
side = -1
branch["x"] = trunk["x"] - 1
else:
side = 1
branch["x"] = trunk["x"] + trunk["width"]
branch["y"] = random.randint(1, math.floor(trunk["height"] / 2)) + (self.height - trunk["height"]) - 1
tree[branch["y"]][branch["x"]] = "#"
# Just sort of squiggle around for a while
branch["length"] = math.floor(self.width / 2)
for i in range(branch["length"]):
direction_determiner = random.randint(0, 10)
direction = {}
if direction_determiner < 8:
direction["x"] = side
direction["y"] = 0
else:
direction["x"] = 0
direction["y"] = -1
branch["x"] += direction["x"]
branch["y"] += direction["y"]
if not (0 <= branch["x"] < self.width) or not (0 <= branch["y"] < self.height):
break
tree[branch["y"]][branch["x"]] = "#"
# Add a leaf sometimes
if branch["y"] < self.height - 2 and random.randint(0, 1):
tree[branch["y"] + 1][branch["x"]] = "."
tree[branch["y"] + 2][branch["x"]] = "."
# Draw the tree
for i in range(self.height):
for j in range(self.width):
print(tree[i][j], end="")
print("")
if __name__ == "__main__":
tree_drawer = Tree()
tree_drawer.draw()
它并不完美,但它可以输出如下内容:
~/tmp $ ./tree.py
## ### #########
.##### .######## ######.... ...
... ..#### .. # #### . .... ...
... .. . .##### ###### .... .
. . . .# . . .### #.... ####
###### . .# . . . .. #.. ##...
.. ..# ########## ##. ####.....
.. ...## . . ..## #. . ## . ..
.. .# . . ....# ###### .. #### .
. ..###### ..# ##############. #....
.. ..### .######## ...############....
.. .. .##### .######## ###.. . ... . .
. .. . ######.#.###### ###. .. . ... .
. . .. . #.########... .
.. . ######## ..
#######
######
######
######
######
######
######
######
######