Animation and Keyboard

Using Keyboard to Move Objects

The statement

x-=10;

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

x=x-10;

Similarly, the statement

x+=10;

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])
            x-=10;
        if (key[KEY_RIGHT])
            x+=10;
        clear_to_color(surface,makecol(255,255,255));
        circlefill(surface,x,200,50,makecol(0,0,255));
        blit(surface, screen,0,0,0,0,SCREEN_W,SCREEN_H);
        rest(20);
        }
    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.