-3

I'm programming now a snake program. I have a little problem in the movement. My direction buttons are the 'W' 'A' 'S' 'D' buttons. I have a direction variable, wich type is char. I read a button from keyboard, direction gets a value, and the snake makes one step from the 4 directions, if I hit one from WASD and then enter. I'd like to fix the enter problem. I want, that my snake moves continually, and doesn't wait for the enter. I'd like to make a timer for direction that way, if I don't hit a character in X milliseconds, then the snake continues to move in the direction of the last value of direction.

How to make this timer? Or any other idea?

lxg
  • 12,375
  • 12
  • 51
  • 73
adam
  • 3
  • 1
  • 1
    What programming language? And please post a reproducible example code of your problem. http://stackoverflow.com/help/how-to-ask – lxg Sep 05 '15 at 18:30
  • To echo @lxg, what code do you have so far? I'm not sure how to answer this without just writing the whole program from scratch and posting it, which is a lot of work. – xdhmoore Sep 05 '15 at 18:37
  • It sounds to me like you're on the right track, though, with the timer idea. I'm not a game developer, but I've heard of timers used similar to that. – xdhmoore Sep 05 '15 at 18:38
  • I'm writing it in C++. – adam Sep 05 '15 at 18:41

2 Answers2

0

Unfortunately, without knowing the language and if an SDK like SDL, XNA, Monogame, etc. are used we can't help. I would suggest trying to search for handling keyboard events. In XNA while the game is running it calls Draw, Update, and Event. Usually the keyboard event would be handled like so:

    //...
    public void Update()
    {
        if(Keyboard.GetStates().IsKeyDown(Keys.W))
        {
            Player.ChangeDirection(Direction.UP);
        }
        //...
        Player.Move();
    }

Player.ChangeDirection(Direction) may will change how the snake moves. The movement is done in the Player.Move() command every time.

EDIT: In C++ are you using any SDKs like SDL, Allegro, DirectX or that?

  • No, It's just a simple console application. My snake is a queue. And it moves in a 10x10 matrix. – adam Sep 05 '15 at 19:00
0

It depends on the language you are programming in :-). Eg. if you have a sleep() or delay() function available, you don't need any special timers and a simple infinite loop will do the job.

The important thing is how you are reading the keyboard. You can read buttons as they are pressed (non-blocking) or waiting for them till they are pressed (blocking). In your case you are reading whole lines - this is why it waits for the enter.

Not sure what is your programming language, but this pseudo-code could explain it a bit. The keyPressed() and readKey() are some fictive library function, which you need to find in your language.

while (true) {
    if (keyPressed()) {
      direction = readKey();
    }
    move(direction);
    sleep(1);
}
Tom
  • 564
  • 1
  • 3
  • 8