大球吃小球
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)
来源:oschina
链接:https://my.oschina.net/u/4382335/blog/3867940