小球碰撞弹回操作加强版

 1 #include "graphics.h"
 2 #include "conio.h"
 3 #include <time.h>
 4 #include <stdlib.h>
 5 #include <stdio.h>
 6 //绘制一个任意反弹的球。这次,将程序修改成屏幕上有 1--10 个任意反弹的球。
 7 
 8 // 注释掉的代码是刚开始犯的错误
 9 // 用注释的代码则产生的效果则是有一个碰到的四周则其他的球也会改变方向
10 struct BALL{
11     int x;
12     int y;
13 };
14 void Drow();
15 int main(){
16     initgraph(640, 480);
17     srand((unsigned)time(NULL));
18     Drow();
19     closegraph();
20     return 0;
21 }
22 
23 void Drow(){
24     
25     BALL ball[10];
26     //int a = 1, b = 1;
27     int a[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
28     int b[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
29     int  i = rand() % 10 + 1;
30     for (int j = 0;j < i; j++){
31         ball[j].x = rand() % 620 + 10;
32         ball[j].y = rand() % 460 + 10;
33     }
34     for (int j = 0; j < i; j++){
35         circle(ball[j].x, ball[i].y, 10);
36     }
37     while (!kbhit()){      
38         for (int j = 0; j < i; j++){
39             setcolor(BLACK);
40             circle(ball[j].x, ball[j].y, 10);
41 
42             if (ball[j].x <= 10 || ball[j].x >= 630){
43                 //a *= -1;
44                 a[j] *= -1;
45             }
46             if (ball[j].y <= 10 || ball[j].y >= 470){
47                 //b *= -1;
48                 b[j] *= -1;
49             }
50             //ball[i].x += a;    
51             //ball[i].y += b;
52             ball[j].x += a[j];
53             ball[j].y += b[j];
54             setcolor(RGB(rand() % 255 + 1, rand() % 255 + 1, rand() % 255 + 1));
55             circle(ball[j].x, ball[j].y, 10);
56         }
57         Sleep(10);
58     }
59 }

 

posted @ 2018-10-19 22:07  浪上了天  阅读(178)  评论(0编辑  收藏  举报