Animation and Keyboard

Using Keyboard to Move Objects

The statement


decreases the value of variable x by 10. It has the same effect as the statement


Similarly, the statement


increases the value of x by 10.

Instead of making a ball move by itself, we can create a program where the ball is moved by pressing the left and right cursor keys. Here is the code fragment that is to replace the part of function main below the install_int statement:

    int x = SCREEN_W/2;
    while (!key[KEY_ESC]) {
        if (key[KEY_LEFT])
        if (key[KEY_RIGHT])
        blit(surface, screen,0,0,0,0,SCREEN_W,SCREEN_H);
    return 0;

Before the while loop, the x position of the ball is set to be in the middle of the screen, horizontally.

The condition key[KEY_LEFT] will be true when the left cursor key is pressed down. In that case, the program will move the ball 10 pixels to the left. In Allegro, there are similar expressions for other keys. For example, to check whether the key B is pressed down, one would use the expression key[KEY_B]. The key is a global variable that is an array and is updated by the Allegro library.

This program is terminated by pressing the Esc key. It cannot be terminated by any key, because that would preclude the use of cursor keys.