1. 程式人生 > >python-pygame的觸碰方法

python-pygame的觸碰方法

[] urn quit set 方法 python AI center ID

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*- 
 3 # Author: ss
 4 
 5 import pygame
 6 import sys
 7 import random
 8 import math
 9 
10 
11 class Ball(pygame.sprite.Sprite):
12     def __init__(self, image, position, speed, bg_size):
13         pygame.sprite.Sprite.__init__(self)
14
self.image = pygame.image.load(image).convert_alpha() 15 self.rect = self.image.get_rect() 16 self.rect.left, self.rect.right = position 17 self.speed = speed 18 self.width, self.height = bg_size[0], bg_size[1] 19 20 def move(self): 21 self.rect = self.rect.move(self.speed)
22 23 if self.rect.right < 0: 24 self.rect.left = self.width 25 if self.rect.left > self.width: 26 self.rect.right = 0 27 if self.rect.bottom < 0: 28 self.rect.top = self.height 29 if self.rect.top > self.height: 30
self.rect.bottom = 0 31 32 def collide_check(item,target): 33 col_balls = [] 34 for each in target: 35 distance = math.sqrt(math.pow((item.rect.center[0] - each.rect.center[0]), 2) + 36 math.pow((item.rect.center[1] - each.rect.center[1]), 2)) 37 if distance <= (item.rect.width + each.rect.width) / 2: 38 col_balls.append(each) 39 return col_balls 40 41 42 def main(): 43 pygame.init() 44 45 ball_image = gray_ball.png 46 bg_image = background.png 47 48 bg_size = width, height = 1024, 681 49 screen = pygame.display.set_mode(bg_size) 50 pygame.display.set_caption(我的滾動的球 -s.s) 51 background = pygame.image.load(bg_image)#.convert_alpha 52 53 balls = [] 54 55 56 for i in range(5): 57 position = random.randint(0, width - 100), random.randint(0, height - 100) 58 speed = [random.randint(-10, 10), random.randint(-10, 10)] 59 ball = Ball(ball_image, position, speed, bg_size) 60 while collide_check(ball,balls): 61 ball.rect.left, ball.rect.right = random.randint(0, width - 100), random.randint(0, height - 100) 62 balls.append(ball) 63 64 65 clock = pygame.time.Clock() 66 67 running = True 68 69 while running: 70 for event in pygame.event.get(): 71 if event.type == pygame.QUIT: 72 sys.exit() 73 74 screen.blit(background, (0, 0)) 75 76 for each in balls: 77 each.move() 78 screen.blit(each.image, each.rect) 79 80 for i in range(5): 81 item = balls.pop(i) 82 if collide_check(item, balls): 83 item.speed[0] = -item.speed[0] 84 item.speed[1] = -item.speed[1] 85 balls.insert(i, item) 86 87 pygame.display.flip() 88 89 clock.tick(50) 90 91 92 if __name__ == "__main__": 93 main()

python-pygame的觸碰方法