In: Computer Science
Draw a landscape image using python coding.
def draw_layers(layers, width, height, color_dict=None): # Default color palette if color_dict is None: color_dict = {'0': (195, 157, 224), '1': (158, 98, 204), '2': (130, 79, 138), '3': (68, 28, 99), '4': (49, 7, 82), '5': (23, 3, 38), '6': (240, 203, 163)} else: # len(color_dict) should be at least: # of layers +1 (background color) if len(color_dict) < len(layers)+1: raise ValueError("Num of colors should be bigger than the num of layers") # Create image into which the terrain will be drawn landscape = Image.new('RGBA', (width, height), color_dict[str(len(color_dict)-1)]) landscape_draw = ImageDraw.Draw(landscape) # Draw the sun landscape_draw.ellipse((50, 25, 100, 75), fill=(255, 255, 255, 255)) # Sample the y values of all x in image final_layers = [] for layer in layers: sampled_layer = [] for i in range(len(layer)-1): sampled_layer += [layer[i]] # If x difference is greater than 1 if layer[i+1][0]-layer[i][0] > 1: # Linearly sample the y values in the range x_[i+1]-x_[i] # This is done by obtaining the equation of the straight # line (in the form of y=m*x+n) that connects two consecutive # points m = float(layer[i+1][1]-layer[i][1])/(layer[i+1][0]-layer[i][0]) n = layer[i][1]-m*layer[i][0] r = lambda x: m*x+n # straight line for j in range(layer[i][0]+1, layer[i+1][0]): # for all missing x sampled_layer += [[j, r(j)]] # Sample points final_layers += [sampled_layer] final_layers_enum = enumerate(final_layers) for final_layer in final_layers_enum: # traverse all x values in the layer for x in range(len(final_layer[1])-1): # for each x value draw a line from its y value to the bottom landscape_draw.line((final_layer[1][x][0], height-final_layer[1][x][1], final_layer[1][x][0], height), color_dict[str(final_layer[0])]) return landscape