tk.update() time.sleep(0.01) if common.is_all_in_target(all_sheep) or step > 2000: for per_sheep in sheep_dict.values(): per_sheep.delete() herd.delete() break step += 1 return step if __name__ == '__main__': """ 选择不同的角度:10, 20, 30, 40, 50, 60, 70 羊群规模设定为:60只 """ tk, canvas = gui.init_tkinter() steps = [] n = 60 theta = math.pi / 4.5 for k in range(1, n): all_sheep, sheep_dict, shepherd_a = init_sheep(canvas, n) step = run_animation(all_sheep, sheep_dict, shepherd_a, theta, k) steps.append(step) print("current theta = {}, and step {}".format(k, step)) print("max double distance animation over!") common.print_list(steps) tk.mainloop()
def run_animation(all_sheep, sheep_dict, herd): step = 0 target = np.array([600, 600]) r_dist = 250 r_rep = 14 speed = 2 n = len(all_sheep) app_dist = n + 50 theta = math.pi / 4.5 fn = math.sqrt(n) * r_rep last_vector = np.zeros((n, 2), dtype=np.float32) # 处理轨迹 UU = [] VV = [] XX = [] YY = [] Px = {} Py = {} for i in range(n): Px['coor' + str(i)] = [] Py['coor' + str(i)] = [] for i in range(n): Px['coor' + str(i)].append(all_sheep[i][0]) Py['coor' + str(i)].append(all_sheep[i][1]) dist_center = 0 dist_shepherd = 0 pre_mean = np.array([np.mean(all_sheep[:, 0]), np.mean(all_sheep[:, 1])]) pre_herd = herd.position2point() while True: herd_point = herd.position2point().copy() if common.check_sector(all_sheep, theta, target) and common.check_dist( all_sheep, target, fn): shepherdR.driving(herd, all_sheep, speed, target, app_dist) else: shepherdR.collecting(herd, all_sheep, speed, app_dist, target) sheepR.sheep_move(herd_point, all_sheep, r_dist, r_rep, speed, sheep_dict, last_vector) tk.update() time.sleep(0.01) if common.is_all_in_target(all_sheep) or step > 4000: for per_sheep in sheep_dict.values(): per_sheep.delete() herd.delete() print("dispersion: ", common.calculate_dispersion(all_sheep)) break # 处理轨迹 global_mean = np.array( [np.mean(all_sheep[:, 0]), np.mean(all_sheep[:, 1])]) dist_center += la.norm(pre_mean - global_mean) pre_mean = global_mean dist_shepherd += la.norm(pre_herd - herd.position2point()) pre_herd = herd.position2point() for i in range(n): Px['coor' + str(i)].append(all_sheep[i][0]) Py['coor' + str(i)].append(all_sheep[i][1]) XX.append(herd.position2point()[0]) YY.append(herd.position2point()[1]) UU.append(global_mean[0]) VV.append(global_mean[1]) step += 1 xx = np.array(XX) yy = np.array(YY) common.print_list(xx) common.print_list(yy) return step