英文:
Accepting only alphanumerics in Golang and ncurses
问题
所以,我正在通过使用ncurses制作一个简单的资源管理游戏来自学一些Golang。我正在使用这个库将Golang连接到ncurses。
我已经创建了一个简单的文本输入面板,它一次接收一个字符,显示它,然后将其添加到组成用户响应的字符串中。下面是它的样子:
// 接收字符,打印字符直到结束
ch := window.GetChar()
kstr := gc.KeyString(ch)
response := ""
cur := 0
for kstr != "enter" {
// 诊断打印以获取当前字符的键码
window.Move(0,0)
window.ClearToEOL()
window.MovePrint(0, 0, ch)
// 如果是退格或删除键,删除一个字符
// 否则,只要是普通字符就添加它
if ((ch == 127 || ch == 8) && cur != 0){
cur--
response = response[:len(response)-1]
window.MovePrint(y, (x + cur), " ")
} else if (ch >= 33 && ch <= 122 && cur <= 52) {
window.MovePrint(y, (x + cur), kstr)
response = response + kstr
cur++
}
// 获取下一个字符
ch = window.GetChar()
kstr = gc.KeyString(ch)
}
然而,箭头和功能键似乎被识别为已与正常的a-zA-Z字符相关联的键码。例如,右箭头被识别为67,F1被识别为80。你有什么想法,我在这里做错了什么,或者是否有更好的方法来通过ncurses接收字母数字字符?我想尽可能避免使用ncurses的字段和类,因为这里的重点是学习Golang,而不是ncurses。谢谢!
英文:
So, I'm teaching myself some Golang by making a simple resource management game with ncurses. I'm using this library to connect Golang to ncurses.
I've made a simple text input panel that takes in one character at a time, displays it, and then adds it to a string composing the user's response. Here's what it looks like:
// Accept characters, printing them until end
ch := window.GetChar()
kstr := gc.KeyString(ch)
response := ""
cur := 0
for kstr != "enter" {
// Diagnostic print to get key code of current character
window.Move(0,0)
window.ClearToEOL()
window.MovePrint(0, 0, ch)
// If its a backspace or delete, remove a character
// Otherwise as long as its a regular character add it
if ((ch == 127 || ch == 8) && cur != 0){
cur--
response = response[:len(response)-1]
window.MovePrint(y, (x + cur), " ")
} else if (ch >= 33 && ch <= 122 && cur <= 52) {
window.MovePrint(y, (x + cur), kstr)
response = response + kstr
cur++
}
// Get next character
ch = window.GetChar()
kstr = gc.KeyString(ch)
}
However, the arrow and function keys seem to be coming up as keycodes already associated with the normal a-zA-Z characters. For example, right-arrow comes up as 67 and F1 as 80. Any ideas what I'm doing wrong here, or if there's a better approach to taking in alphanumerics through ncurses? I'd like to avoid ncurses fields and classes as much as possible, because the point here is to learn Golang, not ncurses. Thanks!
1: https://github.com/rthornton128/goncurses "this library"
答案1
得分: 3
如果您不启用键盘模式,(n)curses将返回组成特殊键的单个字节。
要修复这个问题,请将以下内容添加到您的程序的初始化部分:
stdscr.Keypad(true) // 允许键盘输入
这将返回像右箭头这样的特殊键作为大于255的值。goncurses为这些键定义了符号,例如KEY_RIGHT
。
英文:
If you do not enable the keypad mode, (n)curses will return the individual bytes which make up a special key.
To fix, add this to your program's initialization:
stdscr.Keypad(true) // allow keypad input
which will return special keys such as right-arrow as values above 255. goncurses has symbols defined for those, e.g., KEY_RIGHT
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论