def help(shp, endless_loop_counter=0): coords = shp.exterior.coords[:-1] coords_neg = shp.exterior.coords[:-1] random_selection = [] for i in range(len(coords)): if (not shp.move_restrictions[i]) or (type( shp.move_restrictions[i]) is tuple): random_selection.append(i) choice = random.choice(random_selection) if choice == len(coords) - 1: n2 = 0 else: n2 = choice + 1 n1 = choice - 1 movement = random.uniform(self.min_movement, self.max_movement) movement_neg = movement * (-1) coords[choice] = shape.move_point(coords[choice], coords[n1], coords[n2], movement, shp.move_restrictions[choice]) coords_neg[choice] = shape.move_point( coords_neg[choice], coords_neg[n1], coords_neg[n2], movement_neg, shp.move_restrictions[choice]) s = shape.Shape(coords, shp.interiors, shp.move_restrictions, shp.fixed_displacements, shp.forces) s = shape.even_out_shape(s, 3) s_neg = shape.Shape(coords_neg, shp.interiors, shp.move_restrictions, shp.fixed_displacements, shp.forces) s_neg = shape.even_out_shape(s_neg, 3) while (not s.is_valid) or (not s.is_simple) or ( not s_neg.is_valid) or (not s_neg.is_simple): if movement <= self.min_movement: if endless_loop_counter >= self.max_recursiondepth: return help(shape.round_shape(shp), 0) else: return help(shp, endless_loop_counter + 1) else: coords = shp.exterior.coords[:-1] coords_neg = shp.exterior.coords[:-1] movement = movement / 2 movement_neg = movement_neg / 2 coords[choice] = shape.move_point( coords[choice], coords[n1], coords[n2], movement, shp.move_restrictions[choice]) coords_neg[choice] = shape.move_point( coords_neg[choice], coords_neg[n1], coords_neg[n2], movement_neg, shp.move_restrictions[choice]) s = shape.Shape(coords, shp.interiors, shp.move_restrictions, shp.fixed_displacements, shp.forces) s = shape.even_out_shape(s, 3) #s = round_shape(s, 1) s_neg = shape.Shape(coords_neg, shp.interiors, shp.move_restrictions, shp.fixed_displacements, shp.forces) s_neg = shape.even_out_shape(s_neg, 3) #s_neg =round_shape(s_neg, 1) return random.choice([s, s_neg])
def draw_dest(height): global scene_obj turtle.Screen().addshape("res/img/Road/tree.gif") turtle.Screen().addshape("res/img/Road/rock.gif") scene_obj = [] for i in range(5): scene_obj.append( shape.Shape("res/img/Road/tree.gif", "", "", randint(-1200, 000), 75 + randint(height / 2, 300), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/tree.gif", "", "", randint(000, 600), 75 + randint(height / 2, 300), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/rock.gif", "", "", randint(000, 600), 75 + randint(height / 2, 300), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/rock.gif", "", "", randint(-1200, 000), 75 + randint(height / 2, 300), 1, 1)) for i in range(5): scene_obj.append( shape.Shape("res/img/Road/tree.gif", "", "", randint(-1200, 000), -randint(height / 2, 400), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/tree.gif", "", "", randint(000, 600), -randint(height / 2, 400), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/rock.gif", "", "", randint(000, 600), -randint(height / 2, 400), 1, 1)) scene_obj.append( shape.Shape("res/img/Road/rock.gif", "", "", randint(-1200, 000), -randint(height / 2, 400), 1, 1))
def _get_shape(self, side): """Receives 'left' or 'right': str Prompts for elements (lines and textdots) and a name. Returns the new shape: Shape """ # left shape must not be empty prompt_for_elements = ( 'Select the lines and textdots in the %s shape' % side) guids = rs.GetObjects(prompt_for_elements, rs.filter.curve + rs.filter.textdot) if side == 'left': while guids == None: prompt_for_elements = ( 'The left shape may not be empty. ' + 'Select the lines and textdots in the left shape') guids = rs.GetObjects(prompt_for_elements, rs.filter.curve + rs.filter.textdot) elif side == 'right': if guids == None: guids = [] else: pass line_specs, lpoint_specs = ( self._get_line_specs_and_lpoint_specs(guids)) prompt_for_name = ('Enter the name of the %s shape' % side) name = rs.GetString(prompt_for_name) new_shape = shape.Shape(name, line_specs, lpoint_specs) return new_shape
def get_cool_example(): shell = [(0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (0, 16), (1, 16), (2, 16), (2, 15), (2, 14), (3, 14), (4, 14), (5, 14), (6, 14), (6, 15), (6, 16), (7, 16), (8, 16), (8, 15), (8, 14), (9, 14), (10, 14), (11, 14), (12, 14), (13, 14), (14, 14), (14, 15), (14, 16), (15, 16), (16, 16), (16, 15), (16, 14), (17, 14), (18, 14), (19, 14), (20, 14), (20, 15), (20, 16), (21, 16), (22, 16), (22, 15), (22, 14), (22, 13), (22, 12), (22, 11), (22, 10), (22, 9), (22, 8), (21, 8), (20, 8), (19, 8), (18, 8), (17, 8), (16, 8), (15, 7), (14, 6), (14, 5), (14, 4), (14, 3), (14, 2), (14, 1), (14, 0), (13, 0), (12, 0), (11, 0), (10, 0), (9, 0), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (7, 7), (6, 8), (5, 8), (4, 8), (3, 8), (2, 8), (1, 8)] move_restrictions = [ False, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False ] return shape.Shape(shell, move_restrictions=move_restrictions)
def time_step(self): """Performs a time step. Treats all cases, which can occur.""" if self.active_shape == None: # Erasing full lines. Keys are unbinded as it seems that pressing # a key while erasing lines can cause problems. # erase_full_lines is called until it returns zero since due to # falling of shapes lines can fill again self.unbind_keys() while self.erase_full_lines(): pass self.bind_keys() # Spawing new active shape self.active_shape = shp.Shape(self.next_shape_type) self.shapes_in_canvas.add(self.active_shape) # Choosing and displaying the next shape in the queue self.next_shape_type = random.choice(self.shape_types) self.display_next_shape(self.next_shape_type) # New active shape starts to fall if not self.active_shape.can_move('<down>', self.shapes_in_canvas): self.game_over() else: self.active_shape.move('<down>') self.call_next_time_step() return if self.active_shape.can_move('<down>', self.shapes_in_canvas): self.active_shape.move('<down>') else: self.active_shape = None self.call_next_time_step()
def new_game(self): """Resets the game.""" self.is_game_over = False self.unbind_keys() self.pause() for shape in self.shapes_in_canvas: shape.delete() self.shapes_in_canvas.clear() self.active_shape = shp.Shape(random.choice(self.shape_types)) self.shapes_in_canvas = {self.active_shape} self.next_shape_type = random.choice(self.shape_types) self.display_next_shape(self.next_shape_type) self.canvas.update() self.reset_points() self.time_step_cycle = None time.sleep(0.6) # In case game was previously over self.program.pause_button.config(state='normal') self.bind_keys() self.run()
def value_analyse(self, sec): # cal spot indicator # cal shape print('[{0}]'.format(sec.code)) shape_seri = sec.close_price_seri[-self.shape_period:] print('yesterday price:{0}'.format(shape_seri[-1])) shape_ins = shape.Shape(0.05) (shape_id, shape_name) = shape_ins.what_shape(shape_seri) print("shape:{0}".format(shape_name)) # draw all spot fig, axes = plt.subplots(4, 1, figsize=(20, 40)) for i in range(0, 4): days = self.data_period // 4 * (i + 1) spot_seri = sec.close_price_seri.iloc[-days:] spot_df = ValueStgy.cal_seri_indicator(spot_seri) if shape_seri[-1] > spot_df['leastsq'].iloc[0]: signal = '↓' elif shape_seri[-1] < spot_df['leastsq'].iloc[0]: signal = '↑' else: signal = '-' print('[days:{0}]'.format(days)) print('median:{0}, leastsq:{1}, signal:{2}'.format(spot_df['median'].iloc[0], spot_df['leastsq'].iloc[0], signal)) spot_df.plot(ax=axes[i], title='{0}, days({1})'.format(spot_seri.name, days)) fig.subplots_adjust(top=0.97, bottom=0.05, left=0.04, right=0.97, hspace=0, wspace=0)
def get_realisticreate_example_polygonc_example(): shell = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (14, 1), (14, 2), (14, 3), (13, 3), (12, 3), (11, 3), (10, 3), (9, 3), (8, 3), (7, 3), (6, 3), (5, 3), (4, 3), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (2, 14), (1, 14), (0, 14), (0, 13), (0, 12), (0, 11), (0, 10), (0, 9), (0, 8), (0, 7), (0, 6), (0, 5), (0, 4), (0, 3), (0, 2), (0, 1)] move_restrictions = [ True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True ] forces = [(False, False)] * 17 + [(0, -100)] + [(False, False)] * 38 #forces = [(4,9)]*56 fixed_displacements = [(False, False) ] * 39 + [(True, True)] * 4 + [(False, False)] * 13 return shape.Shape(shell, move_restrictions=move_restrictions, forces=forces, fixed_displacements=fixed_displacements)
def product(self, size, offset): i = random.randint(0, len(self.shapeColor) - 1) j = random.randint(0, len(self.shapeData) - 1) color = self.shapeColor[i] data = self.shapeData[j] shape = vo.Shape(color, data, size, offset) return shape
def merge_example_2(): shell = [(2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (6, 5), (6, 4), (6, 3), (6, 2), (5, 2), (4, 2), (3, 2)] move_restrictions = [ False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False ] return shape.Shape(shell, move_restrictions=move_restrictions)
def merge_example_1(): shell = [(0, 0), (1, 2), (1, 4), (1, 6), (0, 8), (2, 8), (4, 8), (6, 8), (8, 8), (8, 6), (8, 4), (8, 2), (8, 0), (6, 0), (4, 0), (2, 0)] move_restrictions = [ True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False ] return shape.Shape(shell, move_restrictions=move_restrictions)
def updateBallIndicator(): Game.shapes = [] for i in range(0, Game.ballsLeft): mShape = shape.Shape( constants.SHAPE_CIRCLE, (constants.GAMEAREA_X + (constants.BALL_SIZE * 3.0) * (i + 1) - (constants.BALL_SIZE * 2.0)), (constants.GAMEAREA_Y - (constants.BALL_SIZE * 2.0)), constants.BALL_SIZE, constants.BALL_SIZE, constants.BALL_THICKNESS, constants.BALL_COLOR) Game.shapes.append(mShape)
def __init__(self): self.width = 10 self.height = 20 self.background = [] for i in range(self.height): self.background.append([0 for j in range(self.width)]) self.shape = shape.Shape() self.now = self.shape.create(self.shape.random()) self.x = 0 self.y = 4 self.next = self.shape.create(self.shape.random()) self.mark = {0: '□', 1: '■'}
def value_analyse(self, sec): quant_ret = [0, 0, 0] # cal spot indicator # cal shape print('[{0}]'.format(sec.code)) shape_seri = sec.close_price_seri[-self.shape_period:] #print(shape_seri) print('yesterday price:{0}'.format(shape_seri[-1])) shape_ins = shape.Shape(0.05) (shape_id, shape_name) = shape_ins.what_shape(shape_seri) print("shape:{0}".format(shape_name)) profit_list = [] # draw all spot period_list = [360, 180, 90, 30, 7] fig, axes = plt.subplots(len(period_list), 1, figsize=(20, 40)) regime_list = [] for i in range(0, len(period_list)): days = period_list[i] spot_seri = sec.close_price_seri.iloc[-days:] spot_df = ValueStgy.cal_seri_indicator(spot_seri) profit = spot_df['leastsq'].iloc[0] - shape_seri[-1] profit_list.append(profit) regime_list.append(spot_df['leastsq'].iloc[0]) if shape_seri[-1] > spot_df['leastsq'].iloc[0]: signal = '↓' quant_ret[2] += 1 elif shape_seri[-1] < spot_df['leastsq'].iloc[0]: signal = '↑' quant_ret[0] += 1 else: signal = '-' quant_ret[1] += 1 print('[days:{0}]'.format(days)) print('median:{0}, leastsq:{1}, signal:{2}, profit:{3}'.format( spot_df['median'].iloc[0], spot_df['leastsq'].iloc[0], signal, profit)) spot_df.plot(ax=axes[i], title='{0}, days({1})'.format(spot_seri.name, days)) fig.subplots_adjust(top=0.97, bottom=0.05, left=0.04, right=0.97, hspace=0, wspace=0) print('profit: min({0}), max({1})'.format(min(profit_list), max(profit_list))) # regime shape print("[regime shape]") regime_seri = pd.Series(regime_list) (shape_id, shape_name) = shape_ins.what_shape(regime_seri) print("shape:{0}".format(shape_name)) return quant_ret
def get_source_shape(self): """Returns a shape containing the unique elements of the left and right shapes. (This is not an SG shape, so there is no reduction.) Shape ## Accommodate empty right shape """ source_name = '%s-source' % self.name source_line_specs = self._get_source_line_specs() source_lpoint_specs = self._get_source_lpoint_specs() source_shape = shape.Shape(source_name, source_line_specs, source_lpoint_specs) return source_shape
def show_main_menu(f1, f2, f3): global menu_title global menu_subti global menu_calls global menu_items global menu_titbg global menu_chars global menu_visib global menu_runan menu_runan = 0 menu_visib = True menu_titbg = shape.Shape(PATH_MENU_TIT_BG, "", "", 0, 235, 1, 1) menu_title = label.Label("TURTLE RACE", colors.get("title"), 0, 250, 48) menu_subti = label.Label("THE BEST BETTING GAME", colors.get("subti"), 150, 200, 18) menu_calls = [f1, f2, f3] menu_items = [ button.Button(" START ", 0, 30, callback1), button.Button(" SETTINGS ", 0, -30, callback2), button.Button(" ABOUT ", 0, -90, callback3), button.Button(" EXIT ", 0, -150, callback4) ] menu_chars = [ shape.Shape(PATH_MENU_CHAR1[0], "", "", 0, 350, 1, 1), shape.Shape(PATH_MENU_CHAR2[0], "", "", -400, 200, 1, 1), shape.Shape(PATH_MENU_CHAR3[0], "", "", 400, 0, 1, 1), shape.Shape(PATH_MENU_CHAR4[0], "", "", -300, -200, 1, 1), shape.Shape(PATH_MENU_CHAR5[0], "", "", 300, -200, 1, 1), ] menu_char_anim()
def make_sierpinski_init(): name = 'sierpinski-init' line_specs = [((0, 0, 0), (0, 0, 24)), ((0, 0, 0), (0, 18, 0)), ((0, 0, 0), (18, 0, 0)), ((0, 0, 12), (0, 9, 0)), ((0, 0, 12), (0, 9, 12)), ((0, 0, 12), (9, 0, 0)), ((0, 0, 12), (9, 0, 12)), ((0, 0, 24), (0, 18, 0)), ((0, 0, 24), (18, 0, 0)), ((0, 9, 0), (0, 9, 12)), ((0, 9, 0), (9, 0, 0)), ((0, 9, 0), (9, 9, 0)), ((0, 9, 12), (9, 0, 12)), ((0, 9, 12), (9, 9, 0)), ((0, 18, 0), (18, 0, 0)), ((9, 0, 0), (9, 0, 12)), ((9, 0, 0), (9, 9, 0)), ((9, 0, 12), (9, 9, 0))] lpoint_specs = [((3, 12, 4), 'a'), ((3, 3, 16), 'a'), ((3, 3, 4), 'a'), ((6, 6, 8), 'a'), ((12, 3, 4), 'a')] shape_out = shape.Shape(name, line_specs, lpoint_specs) return shape_out
def findEdge(atm, b, rNorm, tip, rotate, gtype, printdot=False): tmp = (b[0]**2 + b[1]**2) try: zQ_Trial = np.arange(math.sqrt(1.0 - tmp) * 1.01, 0.0, -0.005) except ValueError: return None, None pclat_zQ_Trial = [] r_zQ_Trial = [] r_pclat_zQ_Trial = [] hitPlanet = False geoid = shape.Shape(gtype) for zQ in zQ_Trial: if printdot: print('.', end='') sys.stdout.flush() # Q b_vec = np.array([b[0], b[1], zQ]) # --> P b_vec = rotate2planet(rotate, tip, b_vec) r1 = np.linalg.norm(b_vec) * rNorm r_zQ_Trial.append(r1) # get planetocentric latitude/longitude pclat = utils.r2d( math.asin(np.dot(b_vec, yHat) / np.linalg.norm(b_vec))) delta_lng = utils.r2d( math.atan2(np.dot(b_vec, xHat), np.dot(b_vec, zHat))) pclat_zQ_Trial.append(pclat) r2 = geoid.calcShape(atm, rNorm, pclat, delta_lng) r_pclat_zQ_Trial.append(r2) if r1 <= r2: hitPlanet = True break if not hitPlanet: return None, None # interpolate to value xx = np.flipud(np.array(r_zQ_Trial) - np.array(r_pclat_zQ_Trial)) yy = np.flipud(np.array(zQ_Trial[0:len(r_zQ_Trial)])) try: zQ = np.interp(0.0, xx, yy) b = np.array([b[0], b[1], zQ]) edge = rNorm * rotate2planet(rotate, tip, b) except ValueError: b = None edge = None del zQ_Trial, pclat_zQ_Trial, r_zQ_Trial, r_pclat_zQ_Trial, geoid, xx, yy return edge, b # same vector but in P and Q coordinate systems
def main(): #CREATE A SHAPE: red, border (1), name: Generic Shape my_shape = shape.Shape("red", 1, "Generic Shape") #CREATE A CIRCLE: blue, border (2), name: Circle my_circle = circle.Circle("blue", 2, "Circle") #CREATE A SQUARE: yellow, border (3), name: Square my_triangle = triangle.Triangle("yellow", 3, "Triangle") #CREATE A TRIANGLE: orange, border (4), name: Triangle my_square = square.Square("orange", 4, "Square") #ADD CODE TO SET THE APPROPRIATE ATTRIBUTES OF EACH SUBCLASS: #CIRCLE: RADIUS = 4 #SQUARE: SIDE = 5 #TRIANGLE: BASE = 4, HEIGHT = 10 my_circle.set_radius(10) my_triangle.set_height(5) my_triangle.set_base(4) my_square.set_side(10) #ADD CODE TO PRINT THE VALUES OF EACH SHAPE, INCLUDING SHAPE shapes_list = [] shapes_list.append(my_shape) shapes_list.append(my_circle) shapes_list.append(my_triangle) shapes_list.append(my_square) for shapes in shapes_list: print(shapes) #ADD CODE TO PRINT THE AREA OF THE CIRCLE, SQUARE, AND TRIANGLE for shapes in shapes_list: if isinstance(shapes, circle.Circle): print("Circle circumference is:", shapes.calc_circumference()) elif isinstance(shapes, triangle.Triangle): print("Triangle area:", shapes.calc_area()) elif isinstance(shapes, square.Square): print("Square perimeter:", shapes.calc_perimeter()) print(my_circle.calc_area()) print(my_square.calc_area()) print(my_triangle.calc_area())
def pair_shapes(self, shape1, shape2): random_range = 0.2 coords1 = shape1.exterior.coords[:-1] coords2 = shape2.exterior.coords[:-1] coords = [coords1, coords2] if len(coords1) != len(coords2): print( 'Achtung ganz böse Ausnahme hier fehlt noch etwas Programmierarbeit um beide Listen auf die gleich eLänge zu bringen' ) if False: start_points = [] smallest_distance = 9999999 for point1 in coords1: for point2 in coords2: if shape.distance(point1, point2) < smallest_distance: smallest_distance = shape.distance(point1, point2) start_points = [point1, point2] coords_sorted = [] for i in range(2): array = [] j = coords[i].index(start_points[i]) while j < len(coords[i]): array.append(coords[i][j]) j += 1 for point in coords[i]: if point == start_points[i]: break else: array.append(point) coords_sorted.append(array) coords1, coords2 = coords_sorted coords_new = [] for i in range(len(coords1)): coords_new.append( shape.point_between_points(coords1[i], coords2[i], 0.5)) ### Hier muss noch überprüft werden ob denn restrictions usw bei beidne shapes übereinstimmen result_shp = shape.Shape(coords_new, shape1.interiors, shape1.move_restrictions, shape1.fixed_displacements, shape1.forces) if not result_shp.check_shape(): return None return result_shp
def __init__(self, x, y, default_val, number_only = False): self.__selected = False self.__edited = False self.__default_val = default_val self.__string = str(self.__default_val) self.__entry = shape.Shape("square", colors.get("borders"), colors.get("borders"), x, y - 14, self.DEFAULT_WIDTH, 1, 0) self.__text = label.Label(self.__string, colors.get("fg"), x, y, self.DEFAULT_FONT_SIZE) self.__number_only = number_only self.__top_left = [ x - (self.DEFAULT_WIDTH / 2), y + (self.DEFAULT_HEIGHT / 2)] self.__bot_right = [ x + (self.DEFAULT_WIDTH / 2), y - (self.DEFAULT_HEIGHT / 2)] muievent.bind_click(self.__checkclick) muievent.bind_key(self.__checkkeypress)
def display_next_shape(self, type): """Shows next shape in the queue of the type 'type' in the self.next_shape_canvas. Should be used every time type of the next shape is updated.""" i0 = 2 j0 = 1 if type == 'I': i0 += -0.5 j0 += -0.5 elif type == 'O': i0 += 0 j0 += -0.5 self.next_shape_canvas.delete('all') self.next_shape = shp.Shape(type, i0=i0, j0=j0, canvas=self.next_shape_canvas)
def _getshape(self, node): ## shapenode = self._findphyschildnode(parent=node, nodetype="mesh") ## if not shapenode: ## print("Error: shape for node '%s' does not exist." % node.getFullName()) ## sys.exit(11) ## in_nodename = shapenode.getInNode("i", "i")[0] ## if not in_nodename: ## print("Error: input shape for node '%s' does not exist." % shapenode.getFullName()) ## sys.exit(12) ## in_node = self._findglobalnode(in_nodename) in_node = node.shape if not in_node: print("Error: unable to find input shape node '%s'." % in_nodename) sys.exit(13) if not in_node.nodetype in ["polyCube", "polySphere"]: print("Error: input shape node '%s' is of unknown type '%s'." % (in_node.getFullName(), in_node.nodetype)) sys.exit(14) return shape.Shape(node, in_node)
def pair_shapes(self, shp1, shp2, *args): boolean_fncs = [shp1.union, shp1.intersection] if args: if args[0]: polygon_new = boolean_fncs[0](shp2) else: polygon_new = boolean_fncs[1](shp2) else: polygon_new = random.choice(boolean_fncs)(shp2) coords_polygon_new = polygon_new.exterior.coords[:-1] coords_new = [] move_restrictions_new = [] fixed_displacements_new = [] forces_new = [] i = 0 for coord in coords_polygon_new: if coord in shp1.exterior.coords or coord in shp2.exterior.coords: coords_new.append(coord) if coord in shp1.exterior.coords: shp = shp1 elif coord in shp2.exterior.coords: shp = shp2 coords = shp.exterior.coords[:-1] index = coords.index(coord) move_restrictions_new.append(shp.move_restrictions[index]) forces_new.append(shp.forces[index]) fixed_displacements_new.append(shp.fixed_displacements[index]) i += 1 else: if self.change_coords_num_allowed: coords_new.append(coord) # calculate new move restrictions,forces and fixed displacemnts result_shp = shape.Shape(coords_new, move_restrictions=move_restrictions_new, fixed_displacements=fixed_displacements_new, forces=forces_new) if not result_shp.check_shape(): return None return result_shp
def __init__(self, program, window, next_shape_canvas): # Do not change these constants. Their changing is not possible without # a manual change of other parameters - mainly shapes' spawnig position. self.program = program # Which uses an instance of this class self.block_size = sq.Square.a = 30 self.no_rows = sq.Square.num_rows = 20 self.no_columns = sq.Square.num_columns = 15 self.delay = 500 # delay between two subsequent movements down [ms] self.paused = False self.is_game_over = False self.deleted_lines = 0 # Raises level self.lines_text = tkinter.StringVar() # Displayed in lines label self.lines_text.set("Deleted lines: 0") # Increased by points, affects delay and number of new points self.level = 1 self.points = 0 self.points_text = tkinter.StringVar() # Displayed in points label self.points_text.set("Points: 0") # Canvas, Where next shape to spawn is shown, should be set before run self.next_shape_canvas = next_shape_canvas # Main canvas self.canvas_height = self.no_rows * self.block_size self.canvas_width = self.no_columns * self.block_size self.canvas = tkinter.Canvas(window, height=self.canvas_height, width=self.canvas_width, bg='black') self.canvas.grid(row=0, column=0) shp.Shape.primary_canvas = self.canvas self.shape_types = ['I', 'J', 'L', 'S', 'Z', 'O', 'T'] self.active_shape = shp.Shape(random.choice(self.shape_types)) self.next_shape_type = random.choice(self.shape_types) self.display_next_shape(self.next_shape_type) self.shapes_in_canvas = {self.active_shape} self.time_step_cycle = None self.bind_keys()
def _get_shape(self, side): ## Should produce maximal shape """Receives 'initial', 'left', or 'right': str Prompts for elements (lines and textdots) and a name. Returns the new shape: Shape """ prompt_for_elements = ( 'Select the lines and labeled points in the %s shape' % side) guids = rs.GetObjects( prompt_for_elements, rs.filter.curve + rs.filter.annotation + rs.filter.textdot) if side == 'initial': while guids == None: prompt_for_elements = ( 'The initial shape may not be empty. ' + 'Select the lines and labeled points in the initial shape') guids = rs.GetObjects(prompt_for_elements) elif side == 'left': while guids == None: prompt_for_elements = ( 'The left shape may not be empty. ' + 'Select the lines and labeled points in the left shape') guids = rs.GetObjects(prompt_for_elements) elif side == 'right': if guids == None: guids = [] else: pass line_specs, lpoint_specs = ( self._get_line_specs_and_lpoint_specs(guids)) prompt_for_name = ('Enter the name of the %s shape' % side) name = rs.GetString(prompt_for_name) while not self._is_well_formed(name): prompt_for_name = ('The name may not contain a space or a #. ' + 'Enter the name of the %s shape' % side) name = rs.GetString(prompt_for_name) new_shape = shape.Shape(name, line_specs, lpoint_specs) return new_shape
def run(self): # load data for sec in self.concern_sec_list: sec.load_data() fig, axes = plt.subplots(len(self.concern_sec_list), 1, figsize=(20, 40)) for i, sec in enumerate(self.concern_sec_list): # cal shape print('[{0} {1}]'.format(sec.code, sec.name)) shape_seri = sec.close_price_seri[-self.shape_period:] #print(shape_seri) print('yesterday price:{0}'.format(shape_seri[-1])) shape_ins = shape.Shape(0.05) (shape_id, shape_name) = shape_ins.what_shape(shape_seri) print("shape:{0}".format(shape_name)) # draw k spot_seri = sec.close_price_seri spot_df = SimpleStgy.cal_seri_indicator(spot_seri) spot_df.plot(ax=axes[i], title='{0} {1}, days({2})'.format(sec.code, sec.name, self.data_period)) fig.subplots_adjust(top=0.97, bottom=0.05, left=0.04, right=0.97, hspace=0, wspace=0) plt.show()
def __init__(self, charclass, color, name, x, y): self.__anim_stand = [0, 1] self.__anim_run = [2, 5] self.__anim_runback = [6, 9] self.__anim_win = [10, 11] self.__anim_lose = [12, 13] self.__anim_list = [] self.__anim_ind = 0 self.__anim_stick = 0 self.__anim_start = 0 self.__anim_end = 0 self.__anim_delay = 0 self.__load_animation("res/img/" + charclass + "/animation.txt", color) if (color is "Blue"): color = "#55aaff" elif (color is "Green"): color = "#00fcb9" elif (color is "Gray"): color = "#A0A0A0" self.__char_name = label.Label(name, color.lower(), x, y + 65) self.__char_shape = shape.Shape(self.__anim_list[0], "", "", x, y + 15, 64, 64) self.__max_speed = self.DICT_SPEED[config.player_class] self.__min_speed = self.DICT_MIN_SPEED[config.player_class] self.name = name self.color = color self.time = 0.0 self.win = 0 self.lose = 0 self.__pause = True self.__runback = False
def __init__(self, text, x, y, callback, fontsize = 16): h = fontsize + 10 w = len(text * fontsize) self.__autodest = False self.__use_enter = False self.__callback = callback self.__state = "btn_normal" self.__bgbtn = shape.Shape("res/img/Else/button.gif", "", "", x, y, 1, 1) self.__label = label.Label(text, "", x, y, fontsize) self.__color_by_state() self.__top_left = [ x - (w / 2), y + (h / 2)] self.__bot_right = [ x + (w / 2), y - (h / 2)] muievent.bind_click(self.__checkclick) muievent.bind_motion(self.__checkhover) muievent.bind_release(self.__checkrelease)
A. s 변수는 도형이다. B. 반지름이 5인 원을 정의하여 c 변수에 저장한다. C. 가로, 세로가 5, 10인 직사각형을 정의하여 r에 저장한다. D. 세변이 3(밑변), 4, 5이고, 높이가 4인 삼각형을 정의하여 t에 저장한다. E. c의 면적과 둘레를 출력한다. F. r의 면적과 둘레를 출력한다. G. t의 면적과 둘레를 출력한다. H. t의 변들을 리스트로 받아 출력한다. I. 리스트 l을 정의하여, s, c와 r을 요소로 추가한다. J. l의 각 요소에 대해, 해당 요소를 출력하고, 면적과 둘레를 계산하여 출력한다. K. for문 안에서 테스트: getRadius() 메쏘드를 수행한다.(오류 발생) """ # 필요한 module을 수입하기 import shape #shape.py에 정의된 클래스, 함수등을 수입해서 사용하겠다는 의미 확장자는 붙이지 않는다. s = shape.Shape() #shape.의 의미는 "shape.py"에서 정의된 의미 # shape가 shape.py에 정의된 클래스임을 의미 c = shape.Circle(5) r = shape.Rectangle(5, 10) t = shape.Triangle(3, 4, 5, 4) print(s) print(c) print(r) print(t) print(t.getSides()) l = [] l.append(s) l.append(c) l.append(r)