from matplotlib import pyplot as plt
import networkx as nx
import matplotlib
matplotlib.use("Tkagg")

peple = [
    ("贾宝玉", "林黛玉"),("贾宝玉", "薛宝钗"),("林黛玉", "贾母"),("薛宝钗", "薛姨妈"),
    ("王熙凤", "贾琏"),("王熙凤", "贾母"),("贾宝玉", "贾政"),("贾政", "王夫人"),
    ("王夫人", "王熙凤"),("史湘云", "贾母"),("李纨", "贾珠"),("贾珠", "王夫人")
]

peple_set = set()

for i in peple:
    for j in i:
        peple_set.add(j)

people_list = list(peple_set)

G = nx.Graph()
G.add_nodes_from(people_list)
G.add_edges_from(peple)

pos = nx.spring_layout(G)
fig, ax = plt.subplots(figsize=(10, 8))
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)

nx.draw_networkx(G, pos, ax=ax, font_family='STHeiti')

def is_within_bounds(x, y):
    return -1 <= x <= 1 and -1 <= y <= 1

dragging_node = None
last_x, last_y = None, None

def on_press(event):
    global dragging_node, last_x, last_y
    for node, (x, y) in pos.items():
        if (event.xdata - x) ** 2 + (event.ydata - y) ** 2 < 0.05:
            dragging_node = node
            last_x, last_y = event.xdata, event.ydata
            break

def on_move(event):
    global dragging_node, last_x, last_y
    if dragging_node is not None:
        dx = event.xdata - last_x
        dy = event.ydata - last_y
        new_x = pos[dragging_node][0] + dx
        new_y = pos[dragging_node][1] + dy

        if is_within_bounds(new_x,new_y):
            pos[dragging_node] = (new_x,new_y)
            last_x,last_y = event.xdata,event.ydata

            ax.clear()

            nx.draw_networkx(G,pos,ax=ax,font_family='STHeiti')
            plt.draw()

def on_release(event):
    global dragging_node
    dragging_node = None

fig.canvas.mpl_connect('button_press_event',on_press)
fig.canvas.mpl_connect('motion_notify_event',on_move)
fig.canvas.mpl_connect('button_release_event',on_release)

plt.show()