冬日飘雪

跳动的字符_多线程

  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))
  9void Bounce(void* ch);
 10
 11void CheckKey(void* dummy);
 12
 13
 14BOOL repeat = TRUE;
 15HANDLE hStdOut;                //Console handle
 16CONSOLE_SCREEN_BUFFER_INFO    csbi;            //Console info struct
 17
 18void 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
 39void CheckKey(void* dummy)
 40{
 41    _getch();
 42    repeat = FALSE;    //_endthread implied
 43}

 44
 45void 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}

posted on 2010-04-13 23:41 Bomb 阅读(243) 评论(0)  编辑 收藏 引用 所属分类: MultiThread


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


My Links

Blog Stats

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜