views:

39

answers:

3

Hi, another quick question, I want to make simple console based game, nothing too fancy, just to have some weekend project to get more familiar with C. Basically I want to make tetris, but I end up with one problem:

How to let the game engine go, and in the same time wait for input? Obviously cin or scanf is useless for me.

+2  A: 

You're looking for a library such as ncurses.

Many Rogue-like games are written using ncurses or similar.

Mark Rushakoff
A: 

You could work out how to change stdin to non-blocking, which would enable you to write something like tetris, but the game might be more directly expressed in an event-driven paradigm. Maybe it's a good excuse to learn windows programming.

Anyway, if you want to go the console route, if you are using the microsoft compiler, then you should have kbhit() available (via conio.h) which can tell you whether a call to fgetc on stdin would block.

Actually should mention that the MinGW gcc compiler 3.4.5 also supports kbhit().

JustJeff
A: 

There's two ways to do it:

The first is to run two threads; one waits for input and updates state accordingly while the other runs the game.

The other (more common in game development) way is to write the game as one big loop that executes many times a second, updating game state, redrawing the screen, and checking for input.

But instead of blocking when you get key input, you check for the presence of pending keypresses, and if nothing has happened, you just continue through your loop. If you have multiple input sources (keyboard, network, etc.) they all get put there in the loop, checking one after another.

Yes, it's called polling. No, it's not efficient. But high-end games are usually all about pulling the maximum performance and framerates out of the computer, not running cool.

For added efficiency, you can optionally block with a timeout -- saying "wait for a keypress, but no longer than 300 milliseconds" so you can continue on with your loop.

select() comes to mind, but there are other ways of waiting or checking for input as well.

tylerl
Which approach is more efficient? Threading or big loop? My guess would be threading, since from all the background running processes you get more CPU time when multitasking takes place, but thats just my guess.
B.Gen.Jack.O.Neill
In the end, either programming method can lead to the exact same outcome, but threading is probably easier for most people to program, so will probably end up more efficient. The "big loop" method is more common in high-end games because the programmer wants absolute control over the program flow, and threads can lead to a certain amount of unpredictability.
tylerl