simulationgpt.py

Created by alexandre-merle

Created on April 25, 2026

2.11 KB

prgm de simulation de la gravitation


from kandinsky import *
from time import sleep

# -------- PARAMETRES --------
WIDTH, HEIGHT = 320, 222
CENTER_X, CENTER_Y = WIDTH//2, HEIGHT//2

G = 0.05          # constante ajustée
DT = 0.5          # pas de temps
SCALE = 2         # zoom
MIN_DIST = 0.5    # évite division instable

# -------- CLASSE VECTOR --------
class Vec:
    def __init__(self, x, y):
        self.x = x
        self.y = y

# -------- CLASSE PLANETE --------
class Planet:
    def __init__(self, x, y, vx, vy, m, col):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy
        self.ax = 0
        self.ay = 0
        self.m = m
        self.col = col

    def draw(self):
        px = int(self.x * SCALE + CENTER_X)
        py = int(self.y * SCALE + CENTER_Y)
        fill_rect(px-1, py-1, 2, 2, self.col)

# -------- INITIALISATION --------
planets = [
    Planet(0, 0, 0, 0, 5000, (255,255,0)),
    Planet(20, 0, 0, 2, 10, (0,255,255)),
    Planet(-30, 10, -1, 0, 50, (255,0,0))
]

# -------- CALCUL GRAVITE --------
def compute_gravity():
    n = len(planets)
    for i in range(n):
        p = planets[i]
        p.ax = 0
        p.ay = 0

    for i in range(n):
        for j in range(i+1, n):
            p1 = planets[i]
            p2 = planets[j]

            dx = p2.x - p1.x
            dy = p2.y - p1.y

            dist_sq = dx*dx + dy*dy
            if dist_sq < MIN_DIST:
                dist_sq = MIN_DIST

            inv_dist = 1 / (dist_sq ** 0.5)
            inv_dist3 = inv_dist * inv_dist * inv_dist

            force = G * inv_dist3

            fx = dx * force
            fy = dy * force

            p1.ax += fx * p2.m
            p1.ay += fy * p2.m

            p2.ax -= fx * p1.m
            p2.ay -= fy * p1.m

# -------- UPDATE --------
def update():
    compute_gravity()

    for p in planets:
        p.vx += p.ax * DT
        p.vy += p.ay * DT

        p.x += p.vx * DT
        p.y += p.vy * DT

# -------- RENDER --------
def render():
    fill_rect(0, 0, WIDTH, HEIGHT, (0,0,0))
    for p in planets:
        p.draw()

# -------- BOUCLE --------
while True:
    update()
    render()
    sleep(0.05)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.