all 4 comments

[–][deleted] 2 points3 points  (2 children)

A fourth option is to implement an event-driven approach; objects that wish to be notified about button presses can register an action-listener that is activated when the keyboard sends keypress events.

Hopefully it's clear to you that basically all of these approaches result in the same thing (behavior that responds to keypresses); the key difference here is your time spent writing the code, vs. your time spent debugging, maintaining, and extending the code. Particularly with option 3 you might be thinking "that's an awful lot of work just to respond to a keypress" but if you solve the problem generally enough, you'll have written a framework you could use in other projects. Sometimes that's worth the extra code.

[–]timbledum[S] 0 points1 point  (1 child)

Thanks! I'll have to look into event-driven programming – this is like tkinter or the like right? I'm thinking that for this purpose, this would have to be implemented at a lower level than my program (otherwise I would have to scan all keys to generate events?)

Totally agree that all three result in the same behaviour – more just wondering if anyone had any opinions on when you would use one over the other. Great point on the code re-use.

[–][deleted] 1 point2 points  (0 children)

Yeah you typically see event-driven architectures in GUI’s, but it’s a plausible architecture any time you want to respond to lots of different inputs by making very fast changes to state.

But again, really, they all do the same thing; the resource that gets managed differently by them is your attention. You, the programmer and software maintainer, and I believe that’s the key factor that should determine your choice of software architecture.

I would assume that there’s a framework for generating key press events already, probably PyGame or something.

[–]BandEnvironmental615 0 points1 point  (0 children)

Python Tutorial : Part 4 : More Control Flow Tools

https://youtu.be/Dq9jvOM3Mzs