Search code examples
c++openglglut

GLUT pausing the work of keyboard


I'm trying to write "Classic Snake" on GLUT c++ and have some problems.

When my snake goes to right, for instance, and I change the destination to up and in the same time change it to right the snake goes inside itself (I forbid the opportunity to change destination from right to left). I wanted to try to pause the keyboard function after calling for a second but I couldn't find any decision.

I will attach a piece of my code here:

void keyboardSpecial(int k, int x, int y) {
    switch (k) {
        case GLUT_KEY_UP:
            if (snake.dest == UP || snake.dest == DOWN) break;
            else snake.dest = UP;
            break;
        case GLUT_KEY_RIGHT:
            if (snake.dest == LEFT || snake.dest == RIGHT) break;
            else snake.dest = RIGHT;
            break;
        case GLUT_KEY_DOWN:
            if (snake.dest == UP || snake.dest == DOWN) break;
            else snake.dest = DOWN;
            break;
        case GLUT_KEY_LEFT:
            if (snake.dest == LEFT || snake.dest == RIGHT) break;
            else snake.dest = LEFT;
            break;
    }
}

void timer(int) {
    //Eating and growing
    if(snake.sn[snake.size - 1].x == food.pos.x && snake.sn[snake.size - 1].y == food.pos.y) {
        food.eat();
        snake.sn[snake.size].x = snake.sn[snake.size - 1].x;
        snake.sn[snake.size].y = snake.sn[snake.size - 1].y;
        snake.size++;
    }

    //Motion
    for (int i = 1; i < snake.size; i++) {
        snake.sn[i - 1].x = snake.sn[i].x;
        snake.sn[i - 1].y = snake.sn[i].y;
    }
    if (snake.dest == RIGHT) {
        snake.sn[snake.size - 1].x++;
    }
    if (snake.dest == UP) {
        snake.sn[snake.size - 1].y--;
    }
    if (snake.dest == LEFT) {
        snake.sn[snake.size - 1].x--;
    }
    if (snake.dest == DOWN) {
        snake.sn[snake.size - 1].y++;
    }

    //Walls
    if(snake.sn[snake.size - 1].x <= 0) snake.sn[snake.size - 1].x += 640 / dx;
    if(snake.sn[snake.size - 1].x >= 640 / dx) snake.sn[snake.size - 1].x -= 640 / dx;
    if(snake.sn[snake.size - 1].y <= 0) snake.sn[snake.size - 1].y += 480 / dy;
    if(snake.sn[snake.size - 1].y >= 480 / dy) snake.sn[snake.size - 1].y -= 480 / dy;

    //Game Over
    for (int i = 0; i < snake.size - 1; i++) {
        if(snake.sn[snake.size - 1].x == snake.sn[i].x && snake.sn[snake.size - 1].y == snake.sn[i].y) {cout << "Game Over!" << endl;exit(0);}
    }

    display();
    glutTimerFunc(200 - snake.size, timer, 0);
}

Solution

  • Have a saved time value that you compare to at the beginning of the keyboard handler and if not enough time has elapsed simply return. Next, update that value if and only if the key action is accepted.