본문 바로가기

수학 & 코딩

2차원 평면에 임의 반지름을 갖는 임의의 갯수의 공들이 겹치는 부분이 있으면 반발하도록 하는 움직임 - 공간 내에서 입자(공)간 서로 반발하는 현상 모사 - 분자 운동 - 코드 조언은 "chatGPT"로..

728x90

1차 생성된 코드에 대해 조언과 수정은 "chatGPT"를 활용하였음

 

2차원 평면에서 100개의 입자들의 움직임에 대한 예 :

 

 

source python code : 

import pygame, sys
from pygame.locals import *
import time
import random
import numpy as np
import matplotlib.pyplot as plt
import math


def boundary(x0, y0, RAD):
    if RAD < x0 < dis_width-RAD:
        x0 += random.randint((-1)*k, k)
    elif x0 <= RAD:
        x0 += k
    elif x0 >= dis_width-RAD:
        x0 -= k

    if RAD < y0 < dis_height-RAD:
        y0 += random.randint((-1)*k, k)
    elif y0 <= RAD:
        y0 += k
    elif y0 >= dis_height-RAD:
        y0 -= k

    return x0, y0


def points_draw(x, y, N, RAD):
    for i in range(N):
        x0 = x[i]
        y0 = y[i]
        pygame.draw.circle(screen, '#FF0000', [x0, y0], RAD)
        x0, y0 = boundary(x0, y0, RAD)
        x[i] = x0
        y[i] = y0
       
        for j in range(i+1, N):
            x1 = x[j]
            y1 = y[j]
            distance = math.sqrt((x0-x1)**2 + (y0-y1)**2)
           
            if distance < 2*RAD:
                dx = abs(x0 - x1)
                dy = abs(y0 - y1)
               
                if dx < dy:
                    if x0 < x1:
                        x0 -= k
                        x1 += k
                    else:
                        x0 += k
                        x1 -= k
                else:
                    if y0 < y1:
                        y0 -= k
                        y1 += k
                    else:
                        y0 += k
                        y1 -= k
                       
                x[i] = x0
                y[i] = y0
                x[j] = x1
                y[j] = y1


 
pygame.init()

dis_width = 600
dis_height = 600
RAD = 10
N = 100
k = 2

screen = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption(str(N)+' points Simulation')
font = pygame.font.Font("C:\Windows\Fonts\HYSANB.ttf", 20)

FPS = 130
clock = pygame.time.Clock()

x = []
y = []
for i in range(N):
    x.append(random.randint(RAD, dis_width-RAD))
    y.append(random.randint(RAD, dis_height-RAD))
    #x.append(300)
    #y.append(300)


while True: # the main game loop
    screen.fill('#000000')
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    points_draw(x, y, N, RAD)
    pygame.display.update()
    clock.tick(FPS)
   
pygame.quit()
728x90