C++ implementation of the letter game example
- 2020-05-27 06:37:51
- OfStack
This article describes the example of C++ implementation of the alphabet game. I will share it with you for your reference as follows:
// A game of typing letters
// To compile the code, install it first VC Drawing library (V20091123)
#include <graphics.h>
#include <conio.h>
#include <time.h>
// The welcome screen
void welcome()
{
// Output screen prompt
cleardevice();
setcolor(YELLOW);
setfont(64, 0, " blackbody ");
outtextxy(200, 50, " Typing game ");
setcolor(WHITE);
setfont(16, 0, " Song typeface ");
outtextxy(100, 200, " It's a very traditional game where you drop a letter and press the appropriate key and then disappear ");
outtextxy(100, 280, " Function is not very perfect, such as the number of lives, scores and so on are not written ");
outtextxy(100, 320, " Add what you're interested in ");
// Implement flashing "press any key to continue"
int c=255;
while(!kbhit())
{
setcolor(RGB(c, 0, 0));
outtextxy(280, 400, " Press any key to continue ");
c-=8;
if (c<0) c=255;
Sleep(20);
}
getch();
cleardevice();
}
// Exit interface
void goodbye()
{
cleardevice();
setcolor(YELLOW);
setfont(48, 0, " blackbody ");
outtextxy(104, 200, " Write more programs are not young ");
getch();
}
// The main function
void main()
{
// Initialize the screen as 640x480
initgraph(640, 480);
welcome(); // Display welcome screen
srand(time(NULL)); // Set up a random seed
setfont(16, 0, "Arial"); // Sets the font and size of the letters
char target[2] = " "; // Define an alphabetic string
char key; // Define user key variables
// The main loop
while(true)
{
target[0] = 65 + rand() % 26; // Produces any uppercase letter
int x = rand()%630;
for (int y=0; y<460; y++)
{
setcolor(WHITE); // Sets the color of the letters
outtextxy(x, y, target); // According to the letter
if(kbhit())
{
key = getch();
if((key == target[0]) || (key == target[0] + 32))
{
// Set clear
setcolor(BLACK);
outtextxy(x, y, target); // Clear the original character
break; // Break out of the loop and do it 1 A character
}
else if (key == 27)
{
goto EXIT; // If the ESC , exit the main loop of the game
}
}
// Delay, and clear the original character
Sleep(10);
setcolor(BLACK);
outtextxy(x, y, target);
}
}
EXIT:
// Exit part
goodbye();
// Close the graphical interface
closegraph();
}
I hope this article is helpful to you C++ programming.