开发者

Real-time control of Windows Console game

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.


You're looking for a library such as ncurses.

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


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.


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜