Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ConsoleApplication47

.cpp
Скачиваний:
0
Добавлен:
08.10.2015
Размер:
2.93 Кб
Скачать
#include "stdafx.h"
#include <stdlib.h>
#include <glut.h>
#include <math.h>
#include <time.h>
#include <glaux.h>

#define n 2


int w = 800, h = 660;



	struct Ball
{

	int x, y;
	float dx, dy;

	void Draw();
	void move();
	void init(int a, int b, float c, float d);
	void hit(Ball&);

};


Ball mass[n];

void Ball::move()
{
	x += (int)dx;
	y += (int)dy;

	if (x < 0 || x > 740)
	{
		dx *= -1;
		x += dx;
	}

	if (y < 0 || y > 640)
	{
		dy *= -1;
		y += dy;
	}
}
void Ball::Draw()
{
	glColor3f(1.0, 1.0, 0.0);
	glBegin(GL_POLYGON);       
	 glVertex2f(x, y);
	 glVertex2f(x, y + 30);
	 glVertex2f(x + 40, y + 30);
	 glVertex2f(x + 60, y + 15);
	 glVertex2f(x + 40, y);
	glEnd();

	
	
}
void Ball::init(int a, int b, float c, float d)
{
	x = a;
	y = b;
	if (c == 0 && d == 0)
	{
		c = rand() % 6;
		d = rand() % 6;
	}
	dx = c;
	dy = d;
}
void Ball::hit(Ball &ball)
{
	double Dx = ball.x - x;
	double Dy = ball.y - y;
	double d = sqrt(Dx * Dx + Dy * Dy);

	int r1 = 25, r2 = 25;

	if (d < r1 + r2)
	{
		int a, b;
		a = ball.dx;
		b = ball.dy;
		ball.dx = dx;
		ball.dy = dy;
		dx = a;
		dy = b;

	}
}

int check(int i, int j)
{
	double Dx = mass[i].x - mass[j].x;
	double Dy = mass[i].y - mass[j].y;
	double d = sqrt(Dx * Dx + Dy * Dy);

	int r1 = 25, r2 = 25;

	if (d < r1 + r2) return 1;
	else return 0;
}

void create(Ball b, int i)
{

	for (int j(0); j < i; j++)
	{

		while (check(i, j))

		{
			mass[i].x = rand() % 750;
			mass[i].y = rand() % 560;
		}

	}
}

void DrawField()
{
	glBegin(GL_POLYGON);
	glVertex3f(-1.0, -0.3, 0.0);
	glVertex3f(-1.0, 1.0, 0.0);
	glVertex3f(1.0, 1.0, 0.0);
	glVertex3f(1.0, -0.3, 0.0);
	glEnd();

	glColor3f(1.0, 0.0, 0.0);
	glBegin(GL_POLYGON);
	glVertex3f(0.5, 0.0, 0.0);
	glVertex3f(0.5, -0.9, 0.0);
	glVertex3f(-0.5, -0.9, 0.0);
	glVertex3f(-0.5, 0.0, 0.0);
	glEnd();
	//glColor3f(0.0, 0.0, 1.0);

}

void Tick()
{

	for (int i(0); i < n; i++)
		mass[i].move();

	for (int i(0); i < n; i++)
	for (int j = i; j < n; j++)
	if (i != j) mass[i].hit(mass[j]);


}

void display()
{
	glClear(GL_COLOR_BUFFER_BIT);

	for (int i(0); i < n; i++)
	{
		mass[i].Draw();
	}

	DrawField();

	glFlush();
}

void timer(int = 0)
{
	display();
	Tick();
	glutTimerFunc(5, timer, 0);
}

int main(int argc, char **argv)
{
	srand(time(NULL));
	for (int i(0); i < n; i++)
	{
		mass[i].init(rand() % 740, rand() % 540, rand() % 6, rand() % 6);
		create(mass[i], i);
	}

	

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(w, h);
	glutCreateWindow("laba 11");
	glutInitWindowPosition(0, 0);
	glMatrixMode(GL_PROJECTION);
	glClearColor(0.0, 0.0, 1.0, 1.0);
	glLoadIdentity();
	gluOrtho2D(0, w, 0, h);
	glutDisplayFunc(display);
	glutTimerFunc(50, timer, 0);
	glutMainLoop();
}
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]