我正在尝试在Mac OS上使用原生swift(没有任何框架)制作命令行Pong游戏,我需要获得键盘输入。
我正在尝试做这样的事情:当我按下"比如键盘上的按钮程序返回给我类似这样的信息:"A pressed"
在许多主题中,他们使用SwiftUI/Cocoa…但是我不使用框架
谢谢& lt; 3
您需要调整终端行规则(termios)以关闭缓冲并在键入每个字符时提供给您。你可能还想关闭终端回显。
// You said no frameworks. But I'm guessing you'll accept libc.
import Darwin.libc
// Fetch the terminal settings
var term = termios()
tcgetattr(STDIN_FILENO, &term)
// Save them if you need to restore them later
var savedTerm = term
// Turn off canonical input (buffered) and echo
term.c_lflag &= ~(UInt(ICANON) | UInt(ECHO))
// Set the terminal settings immediately
tcsetattr(STDIN_FILENO, TCSANOW, &term)
// Now you can read a character directly
let c = getchar()
// It's an Int32 Unicode code point, so you may want to convert
// it to something more useful
if let input = UnicodeScalar(Int(c)) {
print("Got (input)")
}
// Restore the settings if you need to. Most shells will do this automatically
tcgetattr(STDIN_FILENO, &savedTerm)