如何水平打印出2D ASCII字母

huangapple go评论84阅读模式
英文:

How to print out 2d ascii letters horizontally

问题

我已经将用户输入的2D ASCII字母进行了映射,并尝试以水平方式打印出这些字母,使它们能够并排打印,而不是像现在这样从上到下打印。每个字母的高度为8行,宽度各不相同。我运行了以下代码:go run . "hello"。希望能得到一些帮助。我尝试使用循环遍历表格,但没有成功,还没有找到如何并排打印字母的方法。

你可以使用以下结构体来映射和存储数据:

type letter struct {
	Letter string
	Ascii  int
	Table  [][]string
	Color  []string
}

你可以使用mapFont函数将字体映射到结构体中:

func mapFont(font string) ([]letter, error) {
	// 读取文件内容
	// 将内容按行分割
	// 遍历每一行
		// 如果行为空,则跳过
		// 创建一个二维切片用于存储字符
		// 遍历每个字符
			// 将字符添加到二维切片中
		// 将字母结构体添加到字母切片中
	// 返回字母切片
}

你可以使用mapInput函数将输入映射到字母结构体中:

func mapInput(input string, letters []letter) ([]letter, error) {
	// 将输入按换行符分割成行
	// 创建一个字母切片用于存储映射结果
	// 遍历每一行
		// 将行转换为字符数组
		// 如果行不为空
			// 遍历每个字符
				// 如果字符是ASCII字符
					// 遍历字母切片
						// 如果字母的ASCII码与字符相等
							// 将字母添加到映射结果中
				// 否则,返回错误信息
		// 否则,将空字母添加到映射结果中
	// 返回映射结果
}

你可以使用printLettersSideBySide函数将字母并排打印出来:

func printLettersSideBySide(mapping []letter) {
	// 创建一个空字符串用于存储输出结果
	// 遍历映射结果
		// 遍历字母的每一行
			// 将行连接成字符串并添加到输出结果中
		// 在每个字母之间添加换行符
	// 打印输出结果
}

main函数中,你可以调用上述函数来实现你的需求。

英文:

I have mapped user input with 2d ascii letters and now I am trying to print out ascii letters below horizontally, so they could be printed side by side not top down as they are right now. Letter height is 8 lines and width varies. I run the code go run . "hello" Could really appriciate some help. I have tried to loop over the Table, but no success and haveb't been able to figure out yet how to print letters side by side.

 _      
| |     
| |__   
|  _ \  
| | | | 
|_| |_| 
        
        
       
       
  ___  
 / _ \ 
|  __/ 
 \___| 
       
       
 _  
| | 
| | 
| | 
| | 
|_| 
    
    
 _  
| | 
| | 
| | 
| | 
|_| 
    
    
        
        
  ___   
 / _ \  
| (_) | 
 \___/  
        
        

I use struct for mapping and storying data on that format below:

{h 104 [[ ] [_] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{h 104 [[|] [ ] [|] [ ] [ ] [ ] [ ] [ ]] []}
{h 104 [[|] [ ] [|] [_] [_] [ ] [ ] [ ]] []}
{h 104 [[|] [ ] [ ] [_] [ ] [\] [ ] [ ]] []}
{h 104 [[|] [ ] [|] [ ] [|] [ ] [|] [ ]] []}
{h 104 [[|] [_] [|] [ ] [|] [_] [|] [ ]] []}
{h 104 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{h 104 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{e 101 [[ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{e 101 [[ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{e 101 [[ ] [ ] [_] [_] [_] [ ] [ ]] []}
{e 101 [[ ] [/] [ ] [_] [ ] [\] [ ]] []}
{e 101 [[|] [ ] [ ] [_] [_] [/] [ ]] []}
{e 101 [[ ] [\] [_] [_] [_] [|] [ ]] []}
{e 101 [[ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{e 101 [[ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{l 108 [[ ] [_] [ ] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [_] [|] [ ]] []}
{l 108 [[ ] [ ] [ ] [ ]] []}
{l 108 [[ ] [ ] [ ] [ ]] []}
{l 108 [[ ] [_] [ ] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [ ] [|] [ ]] []}
{l 108 [[|] [_] [|] [ ]] []}
{l 108 [[ ] [ ] [ ] [ ]] []}
{l 108 [[ ] [ ] [ ] [ ]] []}
{o 111 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{o 111 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{o 111 [[ ] [ ] [_] [_] [_] [ ] [ ] [ ]] []}
{o 111 [[ ] [/] [ ] [_] [ ] [\] [ ] [ ]] []}
{o 111 [[|] [ ] [(] [_] [)] [ ] [|] [ ]] []}
{o 111 [[ ] [\] [_] [_] [_] [/] [ ] [ ]] []}
{o 111 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}
{o 111 [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] []}

My code ascii.go:


import (
	"fmt"
	"os"
	"strings"
)

type letter struct {
	Letter string
	Ascii  int
	Table  [][]string
	Color  []string
}

func mapFont(font string) ([]letter, error) {
	readFile, err := os.ReadFile(font)
	if err != nil {
		return nil, fmt.Errorf("could not read the content in the file: %v", err)
	}
	slice := strings.Split(string(readFile), "\n")

	letters := make([]letter, 0)
	index := 31

	for _, row := range slice {
		if row == "" {
			index++
			continue
		}

		grid := make([][]string, 0)

		for _, char := range row {
			grid = append(grid, []string{string(char)})
		}

		letters = append(letters, letter{
			Letter: string(index),
			Ascii:  index,
			Table:  grid,
		})
	}
	return letters, nil
}

func mapInput(input string, letters []letter) ([]letter, error) {
	lines := strings.Split(input, "\\n")
	output := make([]letter, 0)

	for _, line := range lines {
		characters := []rune(line)

		if line != "" {
			for _, ch := range characters {
				if ch >= 32 && ch <= 126 {
					for _, v := range letters {
						if rune(v.Ascii) == ch {
							output = append(output, v)
						}
					}
				} else {
					return nil, fmt.Errorf("input includes non ascii character(s), please use ascii character(s)")
				}
			}
		} else {
			output = append(output, letter{})
		}
	}
	return output, nil
}

func printLettersSideBySide(mapping []letter) {
	output := ""
	for i := 0; i < len(mapping); i++ {
		for j := 0; j < len(mapping[i].Table); j++ {
			output = output + strings.Join(mapping[i].Table[j], "")
		}
		output = output + "\n"
	}

	fmt.Println(output)
}

main.go

package main

import (
	"fmt"
)

func main() {
	args := os.Args

	banners := "banner/standard.txt"
	str := args[1]

	letter, _ := mapFont(banners)
	mapping, _ := mapInput(str, letter)

    printLettersSideBySide(mapping)

	for _, item := range mapping {
		fmt.Println(item)
	}

}

答案1

得分: 1

给其他可能需要的人留下答案:

通过简化类型为letter的Table数据结构,我解决了这个问题。我将[][]string替换为[]string,并在使用该结构的mapFont函数中进行了更改。然后,我添加了一个新的函数来水平打印字母。

ascii.go

import (
    "fmt"
    "os"
    "strings"
)


type letter struct {
    Letter string
    Ascii  int
    Table  []string
}

func mapFont(font string) ([]letter, error) {
    readFile, err := os.ReadFile(font)
    if err != nil {
        return nil, fmt.Errorf("无法读取文件内容:%v", err)
    }
    slice := strings.Split(string(readFile), "\n")

    letters := make([]letter, 0)
    index := 31

    for _, row := range slice {

        if row == "" {
            index++
            continue
        }

        grid := make([]string, 0)

        for _, char := range row {
            grid = append(grid, string(char))
        }

        letters = append(letters, letter{
            Letter: string(index),
            Ascii:  index,
            Table:  grid,
        })
    }
    return letters, nil
}

func mapInput(input string, letters []letter) ([]letter, error) {
    lines := strings.Split(input, "\\n")
    output := make([]letter, 0)

    for _, line := range lines {
        characters := []rune(line)

        if line != "" {
            for _, ch := range characters {
                if ch >= 32 && ch <= 126 {
                    for _, v := range letters {
                        if rune(v.Ascii) == ch {
                            output = append(output, v)
                        }
                    }
                } else {
                    return nil, fmt.Errorf("输入包含非ASCII字符,请使用ASCII字符")
                }
            }
        } else {
            output = append(output, letter{})
        }
    }
    return output, nil
}

func printInput(str string, letter []letter) []string {
    var pixelRows []string

    for row := 0; row < 8; row++ {
        pixelRow := ""

        for letterIndex := 0; letterIndex < len(str); letterIndex++ {

            character, _ := mapInput(string(str[letterIndex]), letter)

            for column := 0; column < len(character[row].Table); column++ {
                pixelRow = pixelRow + character[row].Table[column]
            }

        }
        pixelRows = append(pixelRows, pixelRow)
    }
    return pixelRows
}

main.go

package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args

    banners := "banner/standard.txt"
    str := args[1]

    letter, _ := mapFont(banners)
    sentence, _ := mapInput(str, letter)
    output := printInput(str, sentence)

    for _, v := range output {
        fmt.Println(v)
    }

}

输出:

❯ go run . "hello"
_              _   _          
| |            | | | |         
| |__     ___  | | | |   ___   
|  _ \   / _ \ | | | |  / _ \  
| | | | |  __/ | | | | | (_) | 
|_| |_|  \___| |_| |_|  \___/  
英文:

Leaving answer to others who may need it:

Was able to solve it by making data structure for Table in type letter simpler. Replaced [][]string with []string in and made changes in mapFont function where I used that struct. Then I added new function for printing letters horizontally.

ascii.go

import (
&quot;fmt&quot;
&quot;os&quot;
&quot;strings&quot;
)
type letter struct {
Letter string
Ascii  int
Table  []string
}
func mapFont(font string) ([]letter, error) {
readFile, err := os.ReadFile(font)
if err != nil {
return nil, fmt.Errorf(&quot;could not read the content in the file: %v&quot;, err)
}
slice := strings.Split(string(readFile), &quot;\n&quot;)
letters := make([]letter, 0)
index := 31
for _, row := range slice {
if row == &quot;&quot; {
index++
continue
}
grid := make([]string, 0)
for _, char := range row {
grid = append(grid, string(char))
}
letters = append(letters, letter{
Letter: string(index),
Ascii:  index,
Table:  grid,
})
}
return letters, nil
}
func mapInput(input string, letters []letter) ([]letter, error) {
lines := strings.Split(input, &quot;\\n&quot;)
output := make([]letter, 0)
for _, line := range lines {
characters := []rune(line)
if line != &quot;&quot; {
for _, ch := range characters {
if ch &gt;= 32 &amp;&amp; ch &lt;= 126 {
for _, v := range letters {
if rune(v.Ascii) == ch {
output = append(output, v)
}
}
} else {
return nil, fmt.Errorf(&quot;input includes non ascii character(s), please use ascii character(s)&quot;)
}
}
} else {
output = append(output, letter{})
}
}
return output, nil
}
func printInput(str string, letter []letter) []string {
var pixelRows []string
for row := 0; row &lt; 8; row++ {
pixelRow := &quot;&quot;
for letterIndex := 0; letterIndex &lt; len(str); letterIndex++ {
character, _ := mapInput(string(str[letterIndex]), letter)
for column := 0; column &lt; len(character[row].Table); column++ 
pixelRow = pixelRow + character[row].Table[column]
}
}
pixelRows = append(pixelRows, pixelRow)
}
return pixelRows
}

main.go

package main
import (
&quot;fmt&quot;
&quot;os&quot;
)
func main() {
args := os.Args
banners := &quot;banner/standard.txt&quot;
str := args[1]
letter, _ := mapFont(banners)
sentence, _ := mapInput(str, letter)
output := printInput(str, sentence)
for _, v := range output {
fmt.Println(v)
}
}

Output:

❯ go run . &quot;hello&quot;
_              _   _          
| |            | | | |         
| |__     ___  | | | |   ___   
|  _ \   / _ \ | | | |  / _ \  
| | | | |  __/ | | | | | (_) | 
|_| |_|  \___| |_| |_|  \___/  

huangapple
  • 本文由 发表于 2022年12月28日 18:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/74939200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定