개발 꿀팁/PHP

파이썬 불꽃 코드

Jammie 2022. 7. 18. 15:02
반응형

파이썬 불꽃 코드
다음과 같다

# -*- coding: utf-8 -*-

import math, random,time
import threading
import tkinter as tk
import re
#import uuid

Fireworks=[]
maxFireworks=8
height,width=600,600

class firework(object):
    def __init__(self,color,speed,width,height):
        #uid=uuid.uuid1()
        self.radius=random.randint(2,4)  #입자 반경이 2~4픽셀
        self.color=color   #입자색
        self.speed=speed  #스피드 1.5-3.5초
        self.status=0   #불꽃이 터지지 않은 상태에서,status=0;폭발 후,status>=1;status > 100일 때, 담배의 생명기는 끝난다
        self.nParticle=random.randint(20,30)  #입자 수
        self.center=[random.randint(0,width-1),random.randint(0,height-1)]   #불꽃의 무작위 중심 좌표
        self.oneParticle=[]    #오리지널 파티클 좌표(100% 상태일 때
        self.rotTheta=random.uniform(0,2*math.pi)  #타원 평면 회전각

        #타원 파라미터 방정식:x=a*cos(theta),y=b*sin(theta)
        #ellipsePara=[a,b]

        self.ellipsePara=[random.randint(30,40),random.randint(20,30)]   
        theta=2*math.pi/self.nParticle
        for i in range(self.nParticle):
            t=random.uniform(-1.0/16,1.0/16)  #하나가 생기다 [-1/16,1/16) 의 난수
            x,y=self.ellipsePara[0]*math.cos(theta*i+t), self.ellipsePara[1]*math.sin(theta*i+t)    #타원 파라미터 방정식
            xx,yy=x*math.cos(self.rotTheta)-y*math.sin(self.rotTheta),  y*math.cos(self.rotTheta)+x*math.sin(self.rotTheta)     #평면 회전 방정식
            self.oneParticle.append([xx,yy])
        
        self.curParticle=self.oneParticle[0:]     #현재 파티클 좌표
        self.thread=threading.Thread(target=self.extend)   #스레드 개체 만들기
        

    def extend(self):         #입자군 상태 변화 함수 스레드
        for i in range(100):
            self.status+=1    #상태 ID 업데이트
            self.curParticle=[[one[0]*self.status/100, one[1]*self.status/100] for one in self.oneParticle]   #파티클 그룹 좌표 업데이트
            time.sleep(self.speed/50)
    
    def explode(self):
        self.thread.setDaemon(True)    #현재 스레드를 보호
        self.thread.start()          #시작 스레드
            

    def __repr__(self):
        return ('color:{color}\n'  
                'speed:{speed}\n'
                'number of particle: {np}\n'
                'center:[{cx} , {cy}]\n'
                'ellipse:a={ea} , b={eb}\n'
                'particle:\n{p}\n'
                ).format(color=self.color,speed=self.speed,np=self.nParticle,cx=self.center[0],cy=self.center[1],p=str(self.oneParticle),ea=self.ellipsePara[0],eb=self.ellipsePara[1])


def colorChange(fire):
    rgb=re.findall(r'(.{2})',fire.color[1:])
    cs=fire.status
    
    f=lambda x,c: hex(int(int(x,16)*(100-c)/30))[2:]    #입자의 수명이 70%가 되면 색이 선형적으로 감소하기 시작합니다
    if cs>70:
        ccr,ccg,ccb=f(rgb[0],cs),f(rgb[1],cs),f(rgb[2],cs)
    else:
        ccr,ccg,ccb=rgb[0],rgb[1],rgb[2]
        
    return '#{0:0>2}{1:0>2}{2:0>2}'.format(ccr,ccg,ccb)



def appendFirework(n=1):   #재귀적으로 불꽃놀이 대상을 생성하다
    if n>maxFireworks or len(Fireworks)>maxFireworks:
        pass
    elif n==1:
        cl='#{0:0>6}'.format(hex(int(random.randint(0,16777215)))[2:])   # 0~16777215(0xFFFFFF)의 난수를 랜덤 컬러로 생성
        a=firework(cl,random.uniform(1.5,3.5),width,height)
        Fireworks.append( {'particle':a,'points':[]} )   #파티클 디스플레이 목록 만들기,‘particle'은 불꽃놀이 객체이고, 'points'는 입자마다 표시할 때의 객체 변수 집합이다
        a.explode()
    else:
        appendFirework()
        appendFirework(n-1)


def show(c):
    for p in Fireworks:                #매번 새로고침할 때마다, 먼저 기존의 모든 파티클을 삭제합니다
        for pp in p['points']:
            c.delete(pp)
    
    for p in Fireworks:                #불꽃놀이 대상별로 입자별 표시 대상을 계산하다
        oneP=p['particle']
        if oneP.status==100:        #상태표지 100, 불꽃수명종료
            Fireworks.remove(p)     #현재의 불꽃놀이에서 벗어나다
            appendFirework()           #불꽃놀이 하나를 새로 추가하다
            continue
        else:
            li=[[int(cp[0]*2)+oneP.center[0],int(cp[1]*2)+oneP.center[1]] for cp in oneP.curParticle]       #중심을 원점으로 하는 타원을 임의의 중심 좌표 위로 이동
            color=colorChange(oneP)   #불꽃놀이의 현재 상태를 기준으로 현재 색상 계산하기
            for pp in li:
                p['points'].append(c.create_oval(pp[0]-oneP.radius,  pp[1]-oneP.radius,  pp[0]+oneP.radius,  pp[1]+oneP.radius,  fill=color))  #불꽃놀이 입자 하나하나를 그리다

    root.after(50, show,c)  #콜백, 50ms마다 새로 고침

if __name__=='__main__':
    appendFirework(maxFireworks)
    
    root = tk.Tk()
    cv = tk.Canvas(root, height=height, width=width)
    cv.create_rectangle(0, 0, width, height, fill="black")

    cv.pack()

    root.after(50, show,cv)
    root.mainloop()

사진 전시

반응형

'개발 꿀팁 > PHP' 카테고리의 다른 글

phprsa 암호화 복호화 예제  (0) 2022.07.18
php 레디스 확장 추가  (0) 2022.07.18
HTML에서 PHP를 사용하는 방법  (0) 2022.07.18
kali에서 php 연습하기  (0) 2022.07.18
PHP 파일 및 실행 (PHP 초보자에게 적합)  (0) 2022.07.18