跳动的字符_多线程

跳动的字符_多线程

  1 #include  " windows.h "
  2 #include  " process.h "
  3 #include  " stddef.h "
  4 #include  " stdlib.h "
  5 #include  " conio.h "
  6 #include  " time.h "
  7
  8 #define  GetRandom(min, max) ( (rand()%(int)(((max)+1)-(min))) +(min))
  9 void  Bounce( void *  ch);
 10
 11 void  CheckKey( void *  dummy);
 12
 13
 14 BOOL repeat  =  TRUE;
 15 HANDLE hStdOut;                 // Console handle
 16 CONSOLE_SCREEN_BUFFER_INFO    csbi;             // Console info struct
 17
 18 void  main()
 19 {
 20    CHAR ch = 'A';
 21
 22    hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
 23
 24    //Get the size of screen
 25    GetConsoleScreenBufferInfo(hStdOut,&csbi);
 26
 27    //
 28    _beginthread(CheckKey,0,NULL);
 29
 30
 31    while (repeat)
 32    {
 33        _beginthread(Bounce,0,(void*)(ch++));
 34
 35        Sleep(1000L);
 36    }

 37}

 38
 39 void  CheckKey( void *  dummy)
 40 {
 41    _getch();
 42    repeat = FALSE;    //_endthread implied
 43}

 44
 45 void  Bounce( void *  ch)
 46 {
 47    //select color according to the thread 
 48
 49    char blankcell = 0x20;
 50    char blockcell = (char)ch;
 51    BOOL first = TRUE;
 52    COORD oldCoord, newCoord;
 53    DWORD result;
 54
 55    //
 56    srand((unsigned)time(NULL));
 57
 58    newCoord.X = GetRandom(0,csbi.dwSize.X-1);
 59    newCoord.Y = GetRandom(0,csbi.dwSize.Y-1);
 60
 63
 64    while (repeat)
 65    {
 66        Sleep(100L);
 67
 68        //刷新老位置,在新位置绘制字符
 69        if (first)
 70        {
 71            first = FALSE;
 72        }

 73        else
 74        {
 75            WriteConsoleOutputCharacter(hStdOut,&blankcell,1,oldCoord,&result);
 76            WriteConsoleOutputCharacter(hStdOut,&blockcell,1,newCoord,&result);
 77        }

 78
 79        oldCoord.X = newCoord.X;
 80        oldCoord.Y = newCoord.Y;
 81        newCoord.X += GetRandom(-1,1);
 82        newCoord.Y += GetRandom(-1,1);
 83
 84        if (newCoord.X <0 || newCoord.X == csbi.dwSize.X || newCoord.Y <0 || newCoord.Y == csbi.dwSize.Y)
 85        {
 86            if (newCoord.X < 0)
 87            {
 88                newCoord.X = 1;
 89            }

 90            else if (newCoord.X == csbi.dwSize.X)
 91            {
 92                newCoord.X = csbi.dwSize.X-2;
 93            }

 94
 95            if (newCoord.Y < 0)
 96            {
 97                newCoord.Y = 1;
 98            }

 99            else if (newCoord.Y == csbi.dwSize.Y)
100            {
101                newCoord.Y = csbi.dwSize.Y-2;
102            }

103        }

123        else
124            continue;
125
126        Beep(((char)ch-'A')*100,175);
127    }

128    _endthread();
129
130}

你可能感兴趣的:(跳动的字符_多线程)