大家好,好久没来了,学校有点事情,浪费了我差不多半个假期,前天刚回来,练练手,代码可能有点罗嗦吧。我正在研究bitblt()函数的原理,我想用c实现,顺便请教各位高手。 /* Hit.cpp */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <dos.h> #include <bios.h> #include <graphics.h>
#define SCREEN_HEIGHT 480 #define SCREEN_WIDTH 640
static int dx=1,dy=1; static unsigned int r=20; static unsigned int cx=0,cy=0;
unsigned int randrange(int start,int end) { randomize(); unsigned int ret=start+rand() % (end-start) + 1; return ret; }
void igdrv(void) { int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ } }
void draw_border(void) { setcolor(WHITE); line(0,0,SCREEN_WIDTH-1,0); line(0,0,0,SCREEN_HEIGHT-1); line(0,SCREEN_HEIGHT-1,SCREEN_WIDTH-1,SCREEN_HEIGHT-1); line(SCREEN_WIDTH-1,0,SCREEN_WIDTH-1,SCREEN_HEIGHT-1); }
void draw_ball(void) { cx=randrange(r+1,SCREEN_WIDTH-2-r); cy=randrange(r+1,SCREEN_HEIGHT-2-r); setcolor(WHITE); circle(cx,cy,r); }
void direction(void) { randomize(); dx = (rand() % 100+1) < 50 ? dx : -dx; dy = (rand() % 100+1) < 50 ? dy : -dy; }
void reflect(void) { if(cx==r+1||cx==SCREEN_WIDTH-r-2) dx=-dx; if(cy==r+1||cy==SCREEN_HEIGHT-r-2) dy=-dy; }
int main() { int flag=1,key; igdrv(); // draw the border draw_border(); // first time , draw the ball draw_ball(); // random a direction of action direction(); do { do { delay(2); if(flag) { setcolor(BLACK); circle(cx,cy,r); cx+=dx; cy+=dy; setcolor(WHITE); circle(cx,cy,r);
if((cx==r+1||cx==SCREEN_WIDTH-r-2)||(cy==r+1||cy==SCREEN_HEIGHT-r-2)) { flag=0; } } else { reflect(); flag=1; } } while(!bioskey(1)); // Press esc to exit the program. } while((key=bioskey(0))!=0x11b);
closegraph(); return 0; }