# include # include # include struct StarData { int x, y, dx, dy; }; volatile StarData starData[2]; const int left = 5; const int right = 75; const int top = 2; const int bottom = 22; volatile int key = 0; void gotoxy(int x, int y); HANDLE CreateUpdateThread(int index); DWORD WINAPI UpdateStars(LPVOID data); HANDLE CreateDisplayThread(); DWORD WINAPI DisplayStars(LPVOID data); void DisplayRectangle(); void main() { DisplayRectangle(); HANDLE h1 = CreateUpdateThread(0); HANDLE h2 = CreateUpdateThread(1); HANDLE h3 = CreateDisplayThread(); key = _getch(); CloseHandle(h1); CloseHandle(h2); CloseHandle(h3); } HANDLE CreateUpdateThread(int index) { int x[2] = { (left + right)/3, (left + right)*2/3 }; int y[2] = { (top + bottom) / 3, (top + bottom)*2/3 }; int dx[2] = {1, -1}; int dy[2] = {1, -1}; starData[index].x = x[index]; starData[index].y = y[index]; starData[index].dx = dx[index]; starData[index].dy = dy[index]; return CreateThread(0, 0, UpdateStars, (LPVOID)(starData + index), 0, 0); } HANDLE CreateDisplayThread() { return CreateThread(0, 0, DisplayStars, 0, 0, 0); } void gotoxy(int x, int y) { COORD pos; pos.X = x; pos.Y = y; HANDLE output_handle = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(output_handle, pos); } const int SleepTime = 50; //milli seconds DWORD WINAPI UpdateStars(LPVOID ptr) { StarData* data = (StarData*)ptr; while(!key) { Sleep(SleepTime); data->x += data->dx; if(data->x >= right) { data->x = right - 1; data->dx = -data->dx; } if(data->x <= left) { data->x = left + 1; data->dx = -data->dx; } data->y += data->dy; if(data->y >= bottom) { data->y = bottom - 1; data->dy = -data->dy; } if(data->y <= top) { data->y = top + 1; data->dy = -data->dy; } } return TRUE; } DWORD WINAPI DisplayStars(LPVOID data) { while(!key) { int x0 = starData[0].x; int y0 = starData[0].y; int x1 = starData[1].x; int y1 = starData[1].y; gotoxy(x0, y0); printf("*"); gotoxy(x1, y1); printf("*"); Sleep(SleepTime); gotoxy(x0, y0); printf(" "); gotoxy(x1, y1); printf(" "); } return TRUE; } void DisplayRectangle() { int brick = 177; for(int x = left; x <= right; x++) { gotoxy(x, top); printf("%c", brick); gotoxy(x, bottom); printf("%c", brick); } for(int y = top; y <= bottom; y++) { gotoxy(left-1, y); printf("%c%c", brick, brick); gotoxy(right, y); printf("%c%c", brick, brick); } }