-2

I'm trying to make a command line Pong game in native swift (without any frameworks) on Mac OS and I need to get the keyboard inputs.

I'm trying to do something like that: When I press the "A" button on my keyboard for example The program return me something like: "A pressed".

In many topics, they use SwiftUI/Cocoa ... but I don't use frameworks

Thanks <3

  • On a Mac or iOS? – Fogmeister Oct 19 '21 at 13:39
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 19 '21 at 14:18
  • How are you drawing onto the screen without using some framework? Or is this a console text-only app? (The way you're using to draw on the screen will direct which kind of input tool you should use.) Are you looking for "the `a` key" or are you looking for "the key that would be labeled `A` on a US QWERTY keyboard?" For example, if the user has configured the keyboard layout as AZERTY, which key are you looking for? ("character inputs" is handled differently than "hardware keys") It sounds like you want hardware keys. – Rob Napier Oct 19 '21 at 15:55
  • 1
    @RobNapier it's a command line (text-only) app, and I want chars inputs. Thank u very much for your help – Victor Morel Oct 19 '21 at 16:04
  • I answered this, but realized it's actually a duplicate of Martin R's answer, so I'm duping to that question. Let me know if you believe there's anything more to this question and I'll reopen it. – Rob Napier Oct 19 '21 at 16:54

1 Answers1

1

You'll need to adjust with the terminal line discipline (termios) to turn off buffering and give you each character as it's typed. You'll also probably want to turn off terminal echo.

// 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)
Rob Napier
  • 286,113
  • 34
  • 456
  • 610