使用Go语言生成Excel任务表依赖图(Markdown文件mermaid图)

15 篇文章 0 订阅
6 篇文章 1 订阅

一、前言

在游戏中,任务是非常常见的玩法,可能会有主线任务,支线任务以及其它一些类型的任务,各任务可能还会有前置任务,即需要完成某个任务之后,才能做当前任务。在游戏开发中,配置表可以使用Excel来编辑,如果是任务表,可能会是如下配置方式:

TaskIDTaskTitlePreTask
10任务100
20任务200
11任务1110
21任务2120

当任务比较多的时候,它们的依赖关系将变得不直观,很容易出错,出错也不容易发现。

有没比较直观的方式进行查看,排错呢?笔者想到了目前非常流程的Markdown文件,它可以简单地通过文本的方式输入然后输出强大的各种图表。这里就可以使用mermaid图来直观展现。

关于mermaid图可以去官网https://mermaid.js.org/intro/查看用例。

下图为生成后的效果图:

0:无效任务ID
21:任务21
20:任务20
11:任务11
10:任务10

注意:mermaid图在渲染时,如果不设置subgraph则可能会出现乱序问题,即不是按代码中出现的顺序渲染。

二、实现

为了方便Go读取Excel,需要使用相关的Excel库,笔者使用excelize库。

根据前面的效果图,可以知道,这其实就是一个深度优先的树,实现方式有两种,一种是使用递归的方式来实现,这种方式实现起来简单,但是如果层次很深,那可能会出现栈溢出;另一种方式就是使用栈的方式来实现,将每一层节点先压栈,然后从栈顶取出一个节点然后再将其所有子节点入栈,再从栈顶取出一个节点处理,依此类推,直到栈中所有节点处理完毕。

下面列出使用递归方式实现的版本:

/*
MIT License

# Copyright (c) 2023 WittonBell

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/xuri/excelize/v2"
)

var taskIDField string
var taskTitleField string
var preTaskField string
var noCaseSensitive bool // 是否不区分大小写
var fieldNameRow uint    // 字段名所在行号
var dataStartRow uint    // 数据开始行号

type node struct {
	taskID    string
	taskTitle string
}

type multiMap map[string][]*node

func (slf multiMap) Add(key string, nd *node) {
	if len(slf) == 0 {
		slf[key] = []*node{nd}
	} else {
		slf[key] = append(slf[key], nd)
	}
}

func (slf multiMap) Get(key string) []*node {
	if slf == nil {
		return nil
	}
	return slf[key]
}

func (slf multiMap) Del(key string) {
	delete(slf, key)
}

func searchKeyCol(rows *excelize.Rows) (TaskIDCol, PreTaskIDCol, TitleCol int) {
	row, err := rows.Columns()
	if err != nil {
		fmt.Println(err.Error())
	}

	for i, col := range row {
		name := col
		if noCaseSensitive {
			name = strings.ToLower(col)
		}
		if name == preTaskField {
			PreTaskIDCol = i + 1
		} else if name == taskIDField {
			TaskIDCol = i + 1
		} else if name == taskTitleField {
			TitleCol = i + 1
		}
	}
	return
}

func readExcel(filePath string) multiMap {
	fd, err := excelize.OpenFile(filePath)
	if err != nil {
		fmt.Printf("读取文件`%s`失败", filePath)
		return nil
	}
	defer func() {
		fd.Close()
	}()
	TaskIDCol, PreTaskIDCol, TitleCol := -1, -1, -1
	sheetName := fd.GetSheetName(0)
	rows, err := fd.Rows(sheetName)
	if err != nil {
		return nil
	}
	defer func() {
		rows.Close()
	}()

	m := multiMap{}
	for i := 1; rows.Next(); i++ {
		if i == int(fieldNameRow) {
			TaskIDCol, PreTaskIDCol, TitleCol = searchKeyCol(rows)
			isOk := true
			if TaskIDCol < 0 {
				isOk = false
				fmt.Printf("要求字段名:%s\n", taskIDField)
			}
			if PreTaskIDCol < 0 {
				isOk = false
				fmt.Printf("要求字段名:%s\n", preTaskField)
			}
			if TitleCol < 0 {
				isOk = false
				fmt.Printf("要求字段名:%s\n", taskTitleField)
			}
			if !isOk {
				return nil
			}
		}
		if i < int(dataStartRow) {
			continue
		}
		TaskIDCell, err := excelize.CoordinatesToCellName(TaskIDCol, i)
		if err != nil {
			continue
		}
		PreTaskIDCell, err := excelize.CoordinatesToCellName(PreTaskIDCol, i)
		if err != nil {
			continue
		}

		TitleColCell, err := excelize.CoordinatesToCellName(TitleCol, i)
		if err != nil {
			continue
		}

		TaskID, err := fd.GetCellValue(sheetName, TaskIDCell)
		if err != nil || TaskID == "" {
			continue
		}

		Title, err := fd.GetCellValue(sheetName, TitleColCell)
		if err != nil || Title == "" {
			continue
		}

		PreTaskID, err := fd.GetCellValue(sheetName, PreTaskIDCell)
		if err != nil {
			continue
		}

		if PreTaskID == "" {
			PreTaskID = "0"
		}

		m.Add(PreTaskID, &node{taskID: TaskID, taskTitle: Title})
	}

	return m
}

func usage() {
	w := flag.CommandLine.Output()
	fmt.Fprintf(w, "%s 应用程序是将Excel任务表中的关系转换成Markdown的mermaid图,方便使用Markdown工具直观地查看任务依赖。", filepath.Base(os.Args[0]))
	fmt.Fprintln(w)
	fmt.Fprintf(w, "命令格式:%s -hr [字段所在行号] -dr [数据起始行号] [-nc] -id [任务ID字段名] -t [任务标题字段名] -pid [前置任务ID字段名] -o <输出文件> <Excel文件路径>", filepath.Base(os.Args[0]))
	fmt.Fprintln(w)
	flag.CommandLine.PrintDefaults()
	fmt.Fprintln(w, "  -h")
	fmt.Fprintln(w, "    \t显示此帮助")
}

func main() {
	var outputFile string

	flag.CommandLine.Usage = usage
	flag.BoolVar(&noCaseSensitive, "nc", false, "字段名不区分大小写")
	flag.UintVar(&fieldNameRow, "hr", 1, "字段所在行号")
	flag.UintVar(&dataStartRow, "dr", 2, "数据起始行号")
	flag.StringVar(&taskIDField, "id", "ID", "-id [任务ID字段名]")
	flag.StringVar(&taskTitleField, "t", "Title", "-t [任务标题字段名]")
	flag.StringVar(&preTaskField, "pid", "PreTask", "-pid [前置任务ID字段名]")
	flag.StringVar(&outputFile, "o", "任务图.md", "-o <输出文件>")

	flag.Parse()
	if flag.NArg() < 1 {
		usage()
		return
	}
	if noCaseSensitive {
		taskIDField = strings.ToLower(taskIDField)
		taskTitleField = strings.ToLower(taskTitleField)
		preTaskField = strings.ToLower(preTaskField)
	}
	mapTask := readExcel(flag.Arg(0))
	buildGraph(mapTask, outputFile)
}

func buildGraph(mapTask multiMap, outputFile string) {
	graph := "```mermaid\ngraph TB\n"
	graph += "subgraph  \n"
	root := mapTask.Get("0")
	for _, v := range root {
		graph += visit(rootNodeName, v, mapTask)
	}
	graph += "end\n"
	graph += "```"

	os.WriteFile(outputFile, []byte(graph), os.ModePerm)

	fmt.Println("完成")
}

func visit(parent string, nd *node, mapTask multiMap) string {
	slice := mapTask.Get(nd.taskID)
	graph := fmt.Sprintf("%s --> %s:%s\n", parent, nd.taskID, nd.taskTitle)
	if parent == rootNodeName {
		graph += "subgraph  \n"
	}
	for _, x := range slice {
		graph += visit(fmt.Sprintf("%s:%s", nd.taskID, nd.taskTitle), x, mapTask)
	}
	mapTask.Del(nd.taskID)
	if parent == rootNodeName {
		graph += "end\n"
	}
	return graph
}

使用栈实现的版本笔者放在excelTask2md了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值