CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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