跳到正文

个人记录

threebody-图形库

66xyyd约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v1当前
C++
#include<iostream>
#include<cmath>
#include<graphics.h>
#include<fstream>
using namespace std;
constexpr double fps_speed=60;
constexpr double dt=0.001/fps_speed,g=1;
constexpr int ballnum=3;
constexpr int ScreenHeight=500,ScreenWidth=500;
const string savepath="D:/Data/threebody4/";
PIMAGE pImg;
struct node{
	double x,y,dx,dy;
	double m;
	node(double _x=0,double _y=0,double _dx=0,double _dy=0,double _m=0):x(_x),y(_y),dx(_dx),dy(_dy),m(_m){}
	double distance(const node &other){
		return sqrt((x-other.x)*(x-other.x)+(y-other.y)*(y-other.y));
	}
	double radius() const{
		return sqrt(m/PI);
	}
	void show(double x0,double y0,double k,color_t col=RED) const{
		setfillcolor(col,pImg);
		fillellipse((x-x0)*k+ScreenWidth/2,(y-y0)*k+ScreenHeight/2,radius()*k,radius()*k,pImg);
	}
	void update(const node &other){
		double r=distance(other),G=g*other.m/(r*r),divx=abs(other.x-x)+abs(other.y-y);
		dx+=G*(other.x-x)/divx;
		dy+=G*(other.y-y)/divx;
	}
	void update(){
		x+=dx*dt,y+=dy*dt;
	}
};
constexpr double tmpa=90,tmpb=50;
node balls[ballnum]={
	node(0,-tmpb*sqrt(3),tmpa*sqrt(3),tmpa*3,114),
	node(tmpb,0,-tmpa*sqrt(3)*(sqrt(3)+1),0,114),
	node(-tmpb,0,tmpa*sqrt(3),-tmpa*3,114)
};
color_t ballcolor[ballnum]={
	RED,
	BLUE,
	YELLOW
};
bool update(){
	static node tmp[ballnum]={};
	for(int i=0;i<ballnum;i++){
		tmp[i]=balls[i];
		for(int j=0;j<ballnum;j++){
			if(i==j)	continue;
			if(fabs(tmp[i].distance(balls[j]))<=1e-6)	return false;
			tmp[i].update(balls[j]);
		}
	}
	for(int i=0;i<ballnum;i++){
		balls[i]=tmp[i];
		balls[i].update();
	}
	return true;
}
void show(int id){
	double leftx=balls[0].x,rightx=balls[0].x,upy=balls[0].y,downy=balls[0].y;
	for(int i=1;i<ballnum;i++){
		leftx=min(leftx,balls[i].x-balls[i].radius());
		rightx=max(rightx,balls[i].x+balls[i].radius());
		upy=min(upy,balls[i].y-balls[i].radius());
		downy=max(downy,balls[i].y+balls[i].radius());
	}
	double x0=(rightx+leftx)/2,y0=(downy+upy)/2,k=min(ScreenWidth/(rightx-leftx),ScreenHeight/(downy-upy));
	cout << "x0=" << x0 << ", y0=" << y0 << ", k=" << k << ".\n";
	cleardevice(pImg);
	for(int i=0;i<ballnum;i++){
		balls[i].show(x0,y0,k,ballcolor[i]);
	}
	cleardevice();
	putimage(NULL,0,0,ScreenWidth,ScreenHeight,pImg,0,0);
	const string filename=savepath+to_string(id)+".png";
	savepng(pImg,filename.c_str());
}
int main(){
	initgraph(ScreenWidth,ScreenHeight,INIT_UNICODE|INIT_DEFAULT);
	setcaption((const wchar_t *)u"threebody模拟");
	pImg=newimage(ScreenWidth,ScreenHeight);
	setbkcolor(WHITE,pImg);
	for(int id=1;is_run();delay_fps(fps_speed)){
		for(int i=0,times=1.0/(dt*fps_speed);i<times;i++){
			if(!update())	goto end;
		}
		show(id);
		id++;
	}
	end:getch();
	delimage(pImg);
	closegraph();
	return 0;
}

建好 savepath 中的文件夹就可以了,还可以改参数。需要 EGE 图形库。

原文