-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path086碰撞检测(内置函数实现).py
86 lines (60 loc) · 2.35 KB
/
086碰撞检测(内置函数实现).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import pygame
import sys
from random import *
from pygame.locals import *
class Ball(pygame.sprite.Sprite):
def __init__(self, image, position, speed, bg_size):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
self.speed = speed
self.width, self.height = bg_size
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.right < 0:
self.rect.left = self.width
elif self.rect.left > self.width:
self.rect.right = 0
elif self.rect.bottom < 0:
self.rect.top = self.height
elif self.rect.top > self.height:
self.rect.bottom = 0
def main():
pygame.init()
ball_image = "gray_ball.png"
bg_image = "background.png"
running = True
bg_size = width, height = 1024, 681
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("Play the ball")
background = pygame.image.load(bg_image).convert_alpha()
balls = []
group = pygame.sprite.Group()
for i in range(5):
position = randint(0, width-100), randint(0, height-100)
speed = [randint(-10, 10), randint(-10, 10)]
ball = Ball(ball_image, position, speed, bg_size)
while pygame.sprite.spritecollide(ball, group ,False, pygame.sprite.collide_circle):
ball.rect.left, ball.rect.top = randint(0, width-100), randint(0, height-100)
balls.append(ball)
group.add(ball)
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
screen.blit(background, (0,0))
for each in balls:
each.move()
screen.blit(each.image, each.rect)
for each in group :
group.remove(each)
if pygame.sprite.spritecollide(each, group, False, pygame.sprite.collide_circle):
each.speed[0] = -each.speed[0]
each.speed[1] = -each.speed[1]
group.add(each)
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()