How do I make your program increment repeatedly until another key is pressed in a switch statement

145 views Asked by At

I have been working on one of those snake games and I have a switch statement that says if a key is pressed to move the snake in a direction by incrementing/decrementing, but it will only do that if I hold it. I am looking for a way to have the snakes location keep incrementing without the user holding that key. I put one case below

if(_kbhit()) {
    switch(_getch()) {
        case 'a' : 
        dir = LEFT;
        x--;
3

There are 3 answers

4
2785528 On BEST ANSWER

I am looking for a way to have ... keep incrementing without the user holding that key."

IMHO, you should consider the "select()" function (if it is available in your OS)


Long ago I used "select()" in vxWorks. I see from a man page this function is also available to Ubuntu Linux. (maybe it is available to your system?)

With the select statement, a thread or program can "monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g. input possible). A file descriptor is considered ready if it is possible to perform a corresponding operation (e.g., read() without blocking, or a sufficiently small write())." (from man page)

In practice, the system I worked on had a user interface thread (one of several) issue reads and monitor the input fd (via select) for user input. Our select used a 1/2 second time out (you choose rate). Thus, every half second, if no user input occurred at that port (i.e. device), the time out would release the program to check the bits in the fd_sets.

Nothing prevents the code from doing additional activites in a timeout.

I would guess you will only need to work on readfds, and can leave the other fds empty.

In other words, with select, your code 'monitors' for some user input with a time out, and takes action on either the user input (key stroke) or because of the time out.

This sounds like what you are looking for - action without pressing a key.

0
tinkertime On

Your current design sounds like it moves the snake on press event.

I think you're looking to modify the design such that press events update some current-direction flag, while some background timer thread moves the snake at some regular frame rate.

0
Soviut On

Your code only moves the snake on key press. You need to implement some kind of game loop which moves the snake at a regular interval based on a direction variable. You can then refactor your key press code to simply update the direction.

Pseudo code:

while: # loop forever
    # below could be your switch statement
    if direction == 0: # north
        y--
    if direction == 1: # east
        x++
    if direction == 2: # south
        y++
    if direction == 4: # west
        x--

if _kbhit():
    if _getch() == 'a':
        direction == 4 # west
    # etc...