python-pygame的触碰方法,, 1 #!/usr/
python-pygame的触碰方法,, 1 #!/usr/
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 = position17 self.speed = speed18 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.width25 if self.rect.left > self.width:26 self.rect.right = 027 if self.rect.bottom < 0:28 self.rect.top = self.height29 if self.rect.top > self.height:30 self.rect.bottom = 031 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_balls40 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, 68149 screen = pygame.display.set_mode(bg_size)50 pygame.display.set_caption(‘我的滚动的球 -s.s‘)51 background = pygame.image.load(bg_image)#.convert_alpha52 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 = True68 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的触碰方法
相关内容
- Python之PyQt编程,,1、windows的
- 计算机的基础知识+python安装+pycharm安装+思维导图,,
- 1.1 Python 3 的安装,,1.1 Python
- Python学习-37.Python中的正则表达式,,作为一门现代语言
- 7、python基本数据类型之散列类型,,前言:python的
- python -- Counter 类,,python --
- python练习题,,# 1. 输入平面上
- python中bytes与bytearray以及encode与decode,,一、encode与d
- python基础篇(五),,python基础篇(
- Python 标示符和关键字,, 标示符 开
评论关闭