All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.neko233.skilltree.game.attributeTree.GameAttributeTreeApi Maven / Gradle / Ivy

There is a newer version: 0.3.6
Show newest version
package com.neko233.skilltree.game.attributeTree;

import com.neko233.skilltree.annotation.NotNull;
import com.neko233.skilltree.annotation.Nullable;

import java.util.Collections;
import java.util.Map;

/**
 * 属性树 API
 *
 * @author SolarisNeko
 * Date on 2023-10-14
 */
public interface GameAttributeTreeApi {

    /**
     * @return path to data
     */
    @NotNull
    Map getPathToNodeMap();

    /**
     * 添加属性node
     *
     * @param node 新的 node
     */
    void addAttribute(GameAttributeNode node);

    /**
     * 移除属性node
     *
     * @param path 路径
     */
    void removeAttribute(String path);

    /**
     * 获取属性node
     *
     * @param path 路径
     * @return 获取的属性node
     */
    GameAttributeNode getAttributeNode(String path);

    @NotNull
    default Map getAllAttributeMap() {
        GameAttributeNode root = getPathToNodeMap().get("/root");
        if (root == null) {
            return Collections.emptyMap();
        }
        return root.getAttrMap();
    }

    /**
     * 快捷方法, 获取属性值
     *
     * @param path 路径
     * @param type 类型
     * @return 数值
     */
    default long getAttrValue(String path, String type) {
        Map pathToNodeMap = getPathToNodeMap();
        GameAttributeNode gameAttributeNode = pathToNodeMap.get(path);
        if (gameAttributeNode == null) {
            return 0;
        }
        return gameAttributeNode.getAttrMap().get(type);
    }

    /**
     * 默认查询 parent path 方法
     *
     * @param path 路径
     * @return 父路径
     */
    @Nullable
    default String getParentPath(String path) {
        int lastSeparatorIndex = path.lastIndexOf('/');
        if (lastSeparatorIndex != -1) {
            return path.substring(0, lastSeparatorIndex);
        }
        return null;
    }


    /**
     * 更新父节点的数值, 递归
     *
     * @param updatedNode 更新的节点
     * @param isAdd       true = 添加/ false = 删除
     */
    default void updateParentNodeRecursive(GameAttributeNode updatedNode, boolean isAdd) {
        String parentPath = getParentPath(updatedNode.getPath());
        while (parentPath != null) {
            GameAttributeNode parentNode = getPathToNodeMap().computeIfAbsent(parentPath, GameAttributeNode::createEmpty);
            if (isAdd) {
                parentNode.addAttribute(updatedNode.getAttrMap());
            } else {
                parentNode.minusAttribute(updatedNode.getAttrMap());
            }
            // 递归父路径
            parentPath = getParentPath(parentPath);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy