Good afternoon, I want to do the following: accept user input to the console without pressing the Enter key. I am writing a snake implementation in the console, and for control, you need to enter characters ("w", "a", "s", "d"), but the need to press Enter strongly inhibits the game. How can I implement this in Swift?
1 answer
The solution I found looks like this:
func getKeyPress () -> Int { var key: Int = 0 let c: cc_t = 0 let cct = (c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c) // Set of 20 Special Characters var oldt: termios = termios(c_iflag: 0, c_oflag: 0, c_cflag: 0, c_lflag: 0, c_cc: cct, c_ispeed: 0, c_ospeed: 0) tcgetattr(STDIN_FILENO, &oldt) // 1473 var newt = oldt newt.c_lflag = 1217 // Reset ICANON and Echo off tcsetattr( STDIN_FILENO, TCSANOW, &newt) key = Int(getchar()) // works like "getch()" tcsetattr( STDIN_FILENO, TCSANOW, &oldt) return key } Returns, obviously, the key code.
|