ball.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from enum import Enum, unique
  2. from math import sqrt
  3. from random import randint
  4. import pygame
  5. @unique
  6. class Color(Enum):
  7. """颜色"""
  8. RED = (255, 0, 0)
  9. GREEN = (0, 255, 0)
  10. BLUE = (0, 0, 255)
  11. BLACK = (0, 0, 0)
  12. WHITE = (255, 255, 255)
  13. GRAY = (242, 242, 242)
  14. @staticmethod
  15. def random_color():
  16. """获得随机颜色"""
  17. r = randint(0, 255)
  18. g = randint(0, 255)
  19. b = randint(0, 255)
  20. return (r, g, b)
  21. class Ball(object):
  22. """球"""
  23. def __init__(self, x, y, radius, sx, sy, color=Color.RED):
  24. """初始化方法"""
  25. self.x = x
  26. self.y = y
  27. self.radius = radius
  28. self.sx = sx
  29. self.sy = sy
  30. self.color = color
  31. self.alive = True
  32. def move(self, screen):
  33. """移动"""
  34. self.x += self.sx
  35. self.y += self.sy
  36. if self.x - self.radius <= 0 or self.x + self.radius >= screen.get_width():
  37. self.sx = -self.sx
  38. if self.y - self.radius <= 0 or self.y + self.radius >= screen.get_height():
  39. self.sy = -self.sy
  40. def eat(self, other):
  41. """吃其他球"""
  42. if self.alive and other.alive and self != other:
  43. dx, dy = self.x - other.x, self.y - other.y
  44. distance = sqrt(dx ** 2 + dy ** 2)
  45. if distance < self.radius + other.radius \
  46. and self.radius > other.radius:
  47. other.alive = False
  48. self.radius = self.radius + int(other.radius * 0.146)
  49. def draw(self, screen):
  50. """在窗口上绘制球"""
  51. pygame.draw.circle(screen, self.color,
  52. (self.x, self.y), self.radius, 0)
  53. def main():
  54. # 定义用来装所有球的容器
  55. balls = []
  56. # 初始化导入的pygame中的模块
  57. pygame.init()
  58. # 初始化用于显示的窗口并设置窗口尺寸
  59. screen = pygame.display.set_mode((800, 600))
  60. print(screen.get_width())
  61. print(screen.get_height())
  62. # 设置当前窗口的标题
  63. pygame.display.set_caption('大球吃小球')
  64. # 定义变量来表示小球在屏幕上的位置
  65. x, y = 50, 50
  66. running = True
  67. # 开启一个事件循环处理发生的事件
  68. while running:
  69. # 从消息队列中获取事件并对事件进行处理
  70. for event in pygame.event.get():
  71. if event.type == pygame.QUIT:
  72. running = False
  73. if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  74. x, y = event.pos
  75. radius = randint(10, 100)
  76. sx, sy = randint(-10, 10), randint(-10, 10)
  77. color = Color.random_color()
  78. ball = Ball(x, y, radius, sx, sy, color)
  79. balls.append(ball)
  80. screen.fill((255, 255, 255))
  81. for ball in balls:
  82. if ball.alive:
  83. ball.draw(screen)
  84. else:
  85. balls.remove(ball)
  86. pygame.display.flip()
  87. # 每隔50毫秒就改变小球的位置再刷新窗口
  88. pygame.time.delay(50)
  89. for ball in balls:
  90. ball.move(screen)
  91. for other in balls:
  92. ball.eat(other)
  93. if __name__ == '__main__':
  94. main()