Python

(파이썬) 공 튀기기 (움직이기, 애니메이션)

고니자니 2023. 12. 8. 10:51
반응형

공(Ball) 클래스를 정의하고, 공을 움직이는 코드를 작성합니다.

공(Ball) 클래스는 색상(color), 크기(size) 속성이 있으며, 공을 움직이는 move() 메소드가 있습니다.

공의 개수는 N=40으로 정의하였으며, 공을 움직이는 속도는 main 루프에서 time.sleep() 함수를 이용해서 조정합니다.

from tkinter import *
import random
import time

win = Tk()

canvas=Canvas(win, width=400,height=400)
canvas.pack()

class Ball():
    # 생성자
    def __init__(self, color, size):    
        self.id=canvas.create_oval(0, 0, size, size,fill=color)
        self.dx=random.randint(1,10)
        self.dy=random.randint(1,10)

    def move(self):
        canvas.move(self.id,self.dx,self.dy)
        
        x0, y0, x1, y1 = canvas.coords(self.id)

        # 위쪽, 아래쪽 범위
        if y1 > canvas.winfo_height() or y0 < 0:
            self.dy = -self.dy

        # 왼쪽, 오른쪽 범위
        if x1 > canvas.winfo_width() or x0 < 0:
            self.dx = -self.dx

colors = ["red", "green", "blue", "greenyellow", "magenta", "aqua", "pink","yellow","black", "white"]
ballList = []
N = 40 #볼 개수

for i in range(N):
    ballList.append(Ball(random.choice(colors), random.randint(1, 60)))

while True:
    for i in range(N):
        ballList[i].move()
    win.update()
    time.sleep(0.1)

win.mainloop()

(파이썬) 공 튀기기 (움직이기, 애니메이션)

728x90
반응형