大球吃小球
import pygame import random class Color: @classmethod def random_color(cls): red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) return (red, green, blue) class Ball: def __init__(self, cx, cy, radius, sx, sy, color): self.cx = cx self.cy = cy self.radius = radius self.sx = sx self.sy = sy self.color = color self.is_alive = True # 球的默認存活狀態 # 行為: # 移動 : 在哪里移動 def move(self, window): self.cx += self.sx self.cy += self.sy # 圓心點發生變化 需要做邊界判斷 # 橫向出界 if self.cx - self.radius <= 0 or self.cx + self.radius >= window.get_width(): self.sx = -self.sx # 縱向出界 if self.cy - self.radius <= 0 or self.cy + self.radius >= window.get_height(): self.sy = -self.sy # 吃其他球 def eat_ball(self, other): if self != other and self.is_alive and other.is_alive: # 吃到其他球的條件 兩者圓心點的距離 < 兩者半徑之和 distance = ((self.cx - other.cx) ** 2 + (self.cy - other.cy) ** 2) if distance < ((self.radius + other.radius) ** 2) and self.radius > other.radius: # 吃其他球 other.is_alive = False # 自身半徑在被吃球的半徑的基礎上增加0.14 self.radius += int(other.radius * 0.14) # 出現對應 在界面上畫出對應的一個球 def draw(self, window): pygame.draw.circle(window, self.color, (self.cx, self.cy), self.radius) if __name__ == '__main__': # 畫質屏幕 pygame.init() # 設置屏幕 screen = pygame.display.set_mode((1400, 700)) # 設置屏幕標題 pygame.display.set_caption("大球吃小球") # 定義一容器 存放所有的球 balls = [] isrunning = True while isrunning: for event in pygame.event.get(): if event.type == pygame.QUIT: isrunning = False # 點擊屏幕任意位置 1表示點擊左鍵 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = event.pos # 圓心點 cx = pos[0] cy = pos[1] # 半徑 10-100 radius = random.randint(10, 50) # 速度 sx, sy = random.randint(-5, 5), random.randint(-5, 5) # 顏色 color = Color.random_color() # 根據以上信息創建球 x_ball = Ball(cx, cy, radius, sx, sy, color) balls.append(x_ball) # 刷漆 screen.fill((255, 255, 255)) # 遍歷容器 for b in balls: if b.is_alive: b.draw(screen) else: balls.remove(b) # 渲染 pygame.display.flip() # 設置動畫的時間延遲 pygame.time.delay(50) for b in balls: b.move(screen) for b1 in balls: b.eat_ball(b1)