CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Day01-15/code/Day10/ball.py
Views: 729
from enum import Enum, unique1from math import sqrt2from random import randint34import pygame567@unique8class Color(Enum):9"""颜色"""1011RED = (255, 0, 0)12GREEN = (0, 255, 0)13BLUE = (0, 0, 255)14BLACK = (0, 0, 0)15WHITE = (255, 255, 255)16GRAY = (242, 242, 242)1718@staticmethod19def random_color():20"""获得随机颜色"""21r = randint(0, 255)22g = randint(0, 255)23b = randint(0, 255)24return (r, g, b)252627class Ball(object):28"""球"""2930def __init__(self, x, y, radius, sx, sy, color=Color.RED):31"""初始化方法"""32self.x = x33self.y = y34self.radius = radius35self.sx = sx36self.sy = sy37self.color = color38self.alive = True3940def move(self, screen):41"""移动"""42self.x += self.sx43self.y += self.sy44if self.x - self.radius <= 0 or self.x + self.radius >= screen.get_width():45self.sx = -self.sx46if self.y - self.radius <= 0 or self.y + self.radius >= screen.get_height():47self.sy = -self.sy4849def eat(self, other):50"""吃其他球"""51if self.alive and other.alive and self != other:52dx, dy = self.x - other.x, self.y - other.y53distance = sqrt(dx ** 2 + dy ** 2)54if distance < self.radius + other.radius \55and self.radius > other.radius:56other.alive = False57self.radius = self.radius + int(other.radius * 0.146)5859def draw(self, screen):60"""在窗口上绘制球"""61pygame.draw.circle(screen, self.color,62(self.x, self.y), self.radius, 0)636465def main():66# 定义用来装所有球的容器67balls = []68# 初始化导入的pygame中的模块69pygame.init()70# 初始化用于显示的窗口并设置窗口尺寸71screen = pygame.display.set_mode((800, 600))72print(screen.get_width())73print(screen.get_height())74# 设置当前窗口的标题75pygame.display.set_caption('大球吃小球')76# 定义变量来表示小球在屏幕上的位置77x, y = 50, 5078running = True79# 开启一个事件循环处理发生的事件80while running:81# 从消息队列中获取事件并对事件进行处理82for event in pygame.event.get():83if event.type == pygame.QUIT:84running = False85if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:86x, y = event.pos87radius = randint(10, 100)88sx, sy = randint(-10, 10), randint(-10, 10)89color = Color.random_color()90ball = Ball(x, y, radius, sx, sy, color)91balls.append(ball)92screen.fill((255, 255, 255))93for ball in balls:94if ball.alive:95ball.draw(screen)96else:97balls.remove(ball)98pygame.display.flip()99# 每隔50毫秒就改变小球的位置再刷新窗口100pygame.time.delay(50)101for ball in balls:102ball.move(screen)103for other in balls:104ball.eat(other)105106107if __name__ == '__main__':108main()109110111