实验目的
(1) 进一步掌握数组的定义与使用;进一步掌握函数的定义和函数调用方法;
(2) 学习和掌握结构体的定义和使用方法;
(3) 进一步掌握C语言的编程方法;学习动画程序的基本设计思想和方法。
实验内容
本实验编写一个在控制台窗口中,在不考虑重力的条件下,模拟一组弹球在一个二维封闭房间中运动的程序。
实验代码
C源程序:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <windows.h>
#define PI 3.1415926
struct BALL {
char body[2]; //表示球的两个不同颜色,颜色的取值范围为1至15
int sel; //球当前颜色的色号,即数组body的下标。取值为0或1
int wX; //在二维数组中,球的行坐标位置(整数)
int wY; //在二维数组中,球的列坐标位置(整数)
double X; //球的精确行坐标位置(实数)
double Y; //球的精确列坐标位置(实数)
double dX; //球在x方向的速度(实数)
double dY; //球在y方向的速度(实数)
};
void SetPos(int x, int y)
{
COORD point = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), point);
}
void set_console_color(unsigned short color_index)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_index);
}
int randN1N2(int rN1,int rN2) {
return rand() % (rN2 - rN1 + 1) + rN1;
}
void initCharPicture(char cWin[24][80]) {
int i, j;
for (i = 0; i < 24; i++) {
for (j = 0; j < 80; j++) {
if (j != 79) {
cWin[i][j] = ' ';
}
else {
cWin[i][j] = '\0';
}
}
}
}
void drawBackground(char cWin[24][80]) {
SetPos(0, 0);
set_console_color(0);
int i;
for (i = 0; i < 24; i++) {
printf("%s\n", cWin[i]);
}
}
void initBall(struct BALL ball[], int num) {
int i;
for (i = 0; i < num; i++) {
ball[i].body[0] = randN1N2(1, 15);
ball[i].body[1] = randN1N2(1, 15);
ball[i].sel = randN1N2(0,1);
ball[i].wX = randN1N2(1,22);
ball[i].wY = randN1N2(1,77);
ball[i].X = (double)ball[i].wX;
ball[i].Y = (double)ball[i].wY;
int xita = randN1N2(0, 359);
ball[i].dX = cos(PI * xita / 180);
ball[i].dY = sin(PI * xita / 180);
}
}
void moveBall(struct BALL ball[], int num) {
int i, j;
for (i = 0; i < num; i++) {
ball[i].X += ball[i].dX;
ball[i].Y += ball[i].dY;
ball[i].wX = (int)ball[i].X;
ball[i].wY = (int)ball[i].Y;
if (ball[i].X < 0) {
ball[i].dX = -ball[i].dX;
ball[i].X += ball[i].dX;
}
if (ball[i].X>22) {
ball[i].dX = -ball[i].dX;
ball[i].X += ball[i].dX;
putchar('\7');
}
if (ball[i].Y < 0 || ball[i].Y>77) {
ball[i].dY = -ball[i].dY;
ball[i].Y += ball[i].dY;
}
for (j = 0; j < num; j++) {
if (i != j) {
if (sqrt(pow(ball[i].X - ball[j].X, 2) + pow(ball[i].Y - ball[j].Y, 2) < 1)){
double temp = ball[i].dX;
ball[i].dX = ball[i].dY;
ball[i].dY = temp;
double tmp = ball[j].dX;
ball[j].dX = ball[j].dY;
ball[j].dY = tmp;
ball[i].sel = 1 - ball[i].sel;
ball[j].sel = 1 - ball[j].sel;
}
}
}
}
}
void drawBall(struct BALL ball[], int num) {
int i;
for (i = 0; i < num; i++) {
SetPos(ball[i].wY, ball[i].wX);
set_console_color(ball[i].body[ball[i].sel]);
printf("O");
}
}
int main()
{
char bg[24][80];
struct BALL ball[100];
int n, c = 1000;
srand((unsigned)time(NULL));
printf("请输入弹球的总数:");
scanf("%d", &n);
initCharPicture(bg);
initBall(ball, n);
while (c)
{
drawBackground(bg);
moveBall(ball, n);
drawBall(ball, n);
Sleep(100);
c--;
}
return 0;
}
实验结果
老师点评
1、程序编写基本正确。
2、函数moveBall中,碰撞检测应在所有球都移动后。并且碰撞检测时,内循环应是for(j=i+1;j<num;j++)