Disk Files and Other I/O |
C C C |
|
C9C |
|
C C C |
|
C |
}
}
return (0);
}
First the program and the screen are initialized. Standard stream I/O statements are used because they are easy to use. No sense in doing more work than is necessary! Then the screen is cleared, and the target (the dollar sign) is placed at position 10, 10. The chaser (the question mark) is then placed at position 0, 0, and the game begins.
A while loop polls the keyboard. When a key is pressed, kbhit() returns TRUE, allowing the program to read the keypress, as follows:
if (kbhit())
{/* A key has been pressed, so process it as necessary */ chChar = getch();
if (chChar == (char)NULL)
{
chChar = getch();
If the first call to getch() returns zero, an extended key (probably an arrow key) has been pressed. If the return is nonzero, an ASCII key has been pressed. The only nonextended key that interests us is ESC, which ends the game.
After a key has been pressed, a new location for the chaser is computed. If the chaser has landed on the target’s position, the speaker beeps. Try playing the game— it’s harder than it seems!
If no key has been pressed, the program checks how long it has been since the target moved. Every half second, if no key is pressed, the target moves one square in a random direction. This time period makes the game more playable. (Otherwise, on a fast CPU, the target would be all over the screen, and you could never hit it.)
All moves in ARCADE are kept in the bounds of the screen. In addition, the target cannot move to the same position as the chaser—the game should never lose by its own choice!