Квадратики
Пользователи, просматривающие топик: none
|
Зашли как: Guest
|
Имя |
Сообщение |
<< Старые топики Новые топики >> |
|
|
Квадратики - 2005-04-07 20:54:34
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
Привет! В общем, новая трабла: писала-писала прогу, а в ней всё равно трабл какой-то… Выкладываю код, может быть, кто-нибудь сможет мне чем-то помочь… Суть задачи: должен на экране быть квадрат, движущийся и одновременно вращаюсийся вокруг собственного центра. При столкновении с краями экрана, квадратик должен "зеркально" отражаться от него, продолжая движение. Трабла: при всех анализах квадратик мой всё равно уходит за пределы экрана, потом возвращается… Хелп!!!
……. #include <graphics.h> #include <conio.h> #include <stdio.h> #include <math.h> #include <dir.h>
#define PATH_TO_DRIVER "C:\\TC\\BGI"
#define PI 3.1416 #define ko_x 1 #define ko_y 1
#define ERROR_DATA 2 #define ERROR_GRAPH 1 #define SUCCESS 0
typedef struct CENTER { int x; int y; } CENTER;
typedef struct SQUARE { float ugl; // corner of rotating int half_side; int speed; // speed of moving int p[5][2]; // array of coords of the corners of our rect in current position CENTER center; } SQUARE;
// float Aspectratio() // RET: // x/y // x/y = asp => y = x/asp float Aspectratio(void) { int a, b;
getaspectratio(&a, &b); return (float) a/b; }
// int CheckSquare() // checks the correctness of arguments of user // ARG: // const SQUARE * sq - pointer on struct of our square // float asp = x/y // RET: // ERROR_DATA // SUCCESS - the parameters are correct int CheckSquare(const SQUARE * sq, float asp) { int x_max = getmaxx() - 10; int y_max = getmaxy() - 10;
if ((sq->center.x + sq->half_side > x_max) || ((sq->center.y + sq->half_side) / asp > y_max) || (sq->center.x - sq->half_side < 10) || ((sq->center.y - sq->half_side) / asp < 10) || (sq->half_side <= 0) || (sq->speed <= 5) || (sq->speed > 10000)) return ERROR_DATA;
return SUCCESS; }
// void Init() // initializes the struct''s s parameters // ARG: // SQUARE * sq - pointer on the struct with the square void Init(SQUARE * sq) { int side;
clrscr(); printf("Input the speed of moving: "); scanf("%i", &(sq->speed)); printf("Input x coordinate of the center of the square: "); scanf("%i", &(sq->center.x)); printf("Input y coordinate of the center of the square: "); scanf("%i", &(sq->center.y)); printf("Input the side of the square (in pixels): "); scanf("%i", &side);
sq->half_side = side/2; // how to make without new variable???
sq->ugl = 0.0; }
void Analyze(const SQUARE * sq, int * x, int * y) { int j; int x_max, y_max;
x_max = getmaxx(); y_max = getmaxy();
for (j = 0; j < 4; j++) { if (sq->p[j][0] <= 0 || sq->p[j][0] >= x_max) { *x *= -1; break; } }
for (j = 0; j < 4; j++) { if (sq->p[j][1] <= 0 || sq->p[j][1] >= y_max) { *y *= -1; break; } } return; }
// void Hide() // deletes all the lines // ARG: // sq->p - pointer on the array with the coords of corners of our square void Hide(const SQUARE * sq) { int color = getcolor(); // current color of line
setcolor(getbkcolor()); // change the color of line to color of bаскgrоund drawpoly(5, &(sq->p[0][0])); // draw all the lines of the square by bаскgrоund color setcolor(color); // change the color to the past return; }
// void Show() // draws a current position of the square // ARG: // sq->p - pointer on the array with the coord of corners of our square void Show(const SQUARE * sq) { drawpoly(5, &(sq->p[0][0])); delay(sq->speed); return; }
// void Move() // calculates the current coords of corners of our rect and draws it on the screen // ARG: // SQUARE * sq - pointer on the struct with our square // float asp = x/y // x, y - nes koef of mirror moving void Move(SQUARE * sq, float asp, int x, int y) { int i; // for the cycle
for (i = 0; i <= 3; i++) { sq->p[0] = sq->center.x + (sq->half_side*sin(sq->ugl + PI*1/2*i)*x);<BR> sq->p[1] = (sq->center.y + (sq->half_side*cos(sq->ugl + PI*1/2*i))*y)/asp;<BR> }<BR> sq->p[4][0] = sq->p[0][0];<BR> sq->p[4][1] = sq->p[0][1];<BR><BR> Show(sq);<BR> Hide(sq);<BR><BR> return;<BR>}<BR><BR>int main(void)<BR>{<BR> int gdriver = DETECT; // driver<BR> int gmode; // regim<BR> float asp = Aspectratio(); // asp = x/y<BR> float ang = 0.0; // corner of rotating<BR> int x = 1; // koefs of moving<BR> int y = 1;<BR> SQUARE sq; // struct of our square<BR><BR> Init(&sq); // initializating of struct SQUARE<BR><BR> initgraph(&gdriver, &gmode, PATH_TO_DRIVER);<BR><BR> if (graphresult() != grOk) // check the initialization<BR> {<BR> printf("\nError of graphics initialization.");<BR> getch();<BR> return ERROR_GRAPH;<BR> }<BR><BR> if (CheckSquare(&sq, asp) == ERROR_DATA) // error of arguments<BR> {<BR> closegraph();<BR> printf("Error of parameters.");<BR> getch();<BR> return ERROR_DATA;<BR> }<BR><BR> /* line(0, 0, getmaxx(), 0);<BR> line(0, 0, 0, getmaxy());<BR> line(getmaxx(), 0, getmaxx(), getmaxy());<BR> line(0, getmaxy(), getmaxx(), getmaxy());<BR> delay(1000); */<BR><BR> while(!kbhit()) // if no touch of user<BR> {<BR> Move(&sq, asp, x, y);<BR> Analyze(&sq, &x, &y);<BR> sq.center.x += x*ko_x;<BR> sq.center.y += y*ko_y;<BR> if (ang < PI*2) ang += PI * 0.01;<BR> else ang = 0.0;<BR> sq.ugl = ang;<BR> }<BR><BR> closegraph();<BR> return SUCCESS;<BR>}<BR><BR>
|
|
|
Квадратики - 2005-04-09 00:19:25
|
|
|
4free
Сообщений: 208
Оценки: 0
Присоединился: 2005-03-15 23:04:51
|
Попробовал скомпилировать твой код - компилятор выдает ошибку по применению функции "getaspectratio(&a, &b);". Может здесь чего не так…[sm=sm128.gif]
|
|
|
Квадратики - 2005-04-09 00:31:48
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
А ты попробуй такой код скомпилировать: #include <graphics.h> #include <conio.h> #include <stdio.h> #include <math.h> #include <dir.h>
#define PATH_TO_DRIVER "C:\\TC\\BGI"
#define PI 3.1416 #define ko_x 1 #define ko_y 1
#define ERROR_DATA 2 #define ERROR_GRAPH 1 #define SUCCESS 0
typedef struct CENTER { int x; int y; } CENTER;
typedef struct SQUARE { float ugl; // corner of rotating int half_side; int speed; // speed of moving int p[5][2]; // array of coords of the corners of our rect in current position CENTER center; } SQUARE;
// float Aspectratio() // RET: // x/y // x/y = asp => y = x/asp /* float Aspectratio(void) { int a, b;
getaspectratio(&a, &b); return (float) a/b; } */
// int CheckSquare() // checks the correctness of arguments of user // ARG: // const SQUARE * sq - pointer on struct of our square // float asp = x/y // RET: // ERROR_DATA // SUCCESS - the parameters are correct int CheckSquare(const SQUARE * sq, float asp) { int x_max = getmaxx() - 10; int y_max = getmaxy() - 10;
if ((sq->center.x + sq->half_side > x_max) || ((sq->center.y + sq->half_side) / asp > y_max) || (sq->center.x - sq->half_side < 10) || ((sq->center.y - sq->half_side) / asp < 10) || (sq->half_side <= 0) || (sq->speed <= 5) || (sq->speed > 10000)) return ERROR_DATA;
return SUCCESS; }
// void Init() // initializes the struct's s parameters // ARG: // SQUARE * sq - pointer on the struct with the square void Init(SQUARE * sq) { int side;
clrscr(); printf("Input the speed of moving: "); scanf("%i", &(sq->speed)); printf("Input x coordinate of the center of the square: "); scanf("%i", &(sq->center.x)); printf("Input y coordinate of the center of the square: "); scanf("%i", &(sq->center.y)); printf("Input the side of the square (in pixels): "); scanf("%i", &side);
sq->half_side = side/2; // how to make without new variable???
sq->ugl = 0.0; }
void Analyze(const SQUARE * sq, int * x, int * y) { int j; int x_max, y_max;
x_max = getmaxx(); y_max = getmaxy();
for (j = 0; j < 4; j++) { if (sq->p[j][0] <= 0 || sq->p[j][0] >= x_max) { *x *= -1; break; } }
for (j = 0; j < 4; j++) { if (sq->p[j][1] <= 0 || sq->p[j][1] >= y_max) { *y *= -1; break; } } return; }
// void Hide() // deletes all the lines // ARG: // sq->p - pointer on the array with the coords of corners of our square void Hide(const SQUARE * sq) { int color = getcolor(); // current color of line
setcolor(getbkcolor()); // change the color of line to color of bаскgrоund drawpoly(5, &(sq->p[0][0])); // draw all the lines of the square by bаскgrоund color setcolor(color); // change the color to the past return; }
// void Show() // draws a current position of the square // ARG: // sq->p - pointer on the array with the coord of corners of our square void Show(const SQUARE * sq) { drawpoly(5, &(sq->p[0][0])); delay(sq->speed); return; }
// void Move() // calculates the current coords of corners of our rect and draws it on the screen // ARG: // SQUARE * sq - pointer on the struct with our square // float asp = x/y // x, y - nes koef of mirror moving void Move(SQUARE * sq, float asp, int x, int y) { int i; // for the cycle
for (i = 0; i <= 3; i++) { sq->p[0] = sq->center.x + (sq->half_side*sin(sq->ugl + PI*1/2*i)*x);<BR> sq->p[1] = (sq->center.y + (sq->half_side*cos(sq->ugl + PI*1/2*i))*y)/asp;<BR> }<BR> sq->p[4][0] = sq->p[0][0];<BR> sq->p[4][1] = sq->p[0][1];<BR><BR> Show(sq);<BR> Hide(sq);<BR><BR> return;<BR>}<BR><BR>int main(void)<BR>{<BR> int gdriver = DETECT; // driver<BR> int gmode; // regim<BR> float asp = 1.0; // asp = x/y<BR> float ang = 0.0; // corner of rotating<BR> int x = 1; // koefs of moving<BR> int y = 1;<BR> SQUARE sq; // struct of our square<BR><BR> Init(&sq); // initializating of struct SQUARE<BR><BR> initgraph(&gdriver, &gmode, PATH_TO_DRIVER);<BR><BR> if (graphresult() != grOk) // check the initialization<BR> {<BR> printf("\nError of graphics initialization.");<BR> getch();<BR> return ERROR_GRAPH;<BR> }<BR><BR> if (CheckSquare(&sq, asp) == ERROR_DATA) // error of arguments<BR> {<BR> closegraph();<BR> printf("Error of parameters.");<BR> getch();<BR> return ERROR_DATA;<BR> }<BR><BR> /* line(0, 0, getmaxx(), 0);<BR> line(0, 0, 0, getmaxy());<BR> line(getmaxx(), 0, getmaxx(), getmaxy());<BR> line(0, getmaxy(), getmaxx(), getmaxy());<BR> delay(1000); */<BR><BR> while(!kbhit()) // if no touch of user<BR> {<BR> Move(&sq, asp, x, y);<BR> Analyze(&sq, &x, &y);<BR> sq.center.x += x*ko_x;<BR> sq.center.y += y*ko_y;<BR> if (ang < PI*2) ang += PI * 0.01;<BR> else ang -= 2*PI;<BR> sq.ugl = ang;<BR> }<BR><BR> closegraph();<BR> return SUCCESS;<BR>}<BR><BR>
|
|
|
Квадратики - 2005-04-09 00:34:36
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
Я просто убрала ту функцию. В ней, в принципе, проблем быть не может. Точнее, ошибка в алгоритме в первую очередь, а не в реализации. Посмотри, как в этом случае будет работать. (Путь к драйверам не забудь в дефайнах изменить на правильный). Бага появляется, когда квадратик начинает "дрыгаться" у стенок, а должен - просто отталкиваться от них. А получается - когда правильно, а когда - не очень… :(
|
|
|
Квадратики - 2005-04-09 00:35:14
|
|
|
4free
Сообщений: 208
Оценки: 0
Присоединился: 2005-03-15 23:04:51
|
/* float Aspectratio(void) Это у тебя комментарий или объявление функции? Если объявление , то где она сама?[sm=sm128.gif]
|
|
|
Квадратики - 2005-04-09 00:36:42
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
Блин, в первом листинге была сама функция, а над ней -комменты. Сейчас я функцию закомментила. Её просто, считай нет. Вот.
|
|
|
Квадратики - 2005-04-09 00:40:43
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
Это, если что - стукай в асю: 249 - 931 - 249.
|
|
|
Квадратики - 2005-04-09 00:49:38
|
|
|
4free
Сообщений: 208
Оценки: 0
Присоединился: 2005-03-15 23:04:51
|
Второй листинг просто убил мой компилятор сообщениями -128 J:\dосиmеnts and Settings\Dev-Cpp\Edelweiss1.cpp `setcolor' undeclared (first use this function) -129 J:\dосиmеnts and Settings\Dev-Cpp\Edelweiss1.cpp `drawpoly' undeclared (first use this function) и т.д.[sm=sm128.gif]
|
|
|
Квадратики - 2005-04-09 00:52:05
|
|
|
4free
Сообщений: 208
Оценки: 0
Присоединился: 2005-03-15 23:04:51
|
quote:
—————-<BR>Цитата: Дата:09.04.2005 0:40:43, Автор:Edelweiss :: &amp;#1069;то, если что - стукай в асю: 249 - 931 - 249. —————-
На самом деле я практически только начал пробовать на вкус С/С++ , поэтому буду плохим советчиком…Наверное…[sm=sm128.gif]
|
|
|
Квадратики - 2005-04-09 01:50:22
|
|
|
rgo
Сообщений: 7170
Оценки: 281
Присоединился: 2004-09-25 05:14:25
|
Я думаю здесь следующая бага: вряд ли угол квадрата совпадёт с границей экрана. И программа построена так, что отражение произойдёт только после того как этот угол вылезет за границу… И соответственно на следующей итерации произойдёт повторное отражение (угол то так там и остался). Уже никому не нужное. Надо проверять новые координаты, до движения квадрата. Или отменять движение если квадрат вылез за границу.
|
|
|
Квадратики - 2005-04-09 02:54:47
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
У нас, скорее всего, разные компиляторы… Так как все эти функции - библиотечные.
|
|
|
Квадратики - 2005-04-09 03:17:35
|
|
|
4free
Сообщений: 208
Оценки: 0
Присоединился: 2005-03-15 23:04:51
|
quote:
—————-<BR>Цитата: Дата:09.04.2005 2:54:47, Автор:Edelweiss :: У нас, скорее всего, разные компиляторы… Так как все эти функции - библиотечные. —————-
#include <graphics.h> #include <conio.h> #include <stdio.h> #include <math.h> #include <dir.h> В какую из объявленных они входят?…
|
|
|
Квадратики - 2005-04-09 03:24:26
|
|
|
Edelweiss
Сообщений: 174
Оценки: 0
Присоединился: 2005-01-11 22:14:41
|
aspectratio() = conio.h setcolor() и пр.. - graphics.h Кстати, dir.h лучше изменить на dos.h У меня стоит Борланд Си.
|
|
|
|
|