1#!/usr/bin/env python2#-*-coding:utf-8-*-3 # Author:ss4 5 Import Pygame6 Import SYS7 Import Random8 Import Math9 Ten One classBall (pygame.sprite.Sprite): A def __init__ (self, image, position, speed, bg_size): - pygame.sprite.sprite.__init__ (self) -Self.image =pygame.image.load (image). Convert_alpha () theSelf.rect =Self.image.get_rect () -Self.rect.left, self.rect.right =position -Self.speed = Speed -Self.width, self.height = bg_size[0], bg_size[1] + - def Move (self): +Self.rect =Self.rect.move (self.speed) A at ifSelf.rect.right <0: -Self.rect.left =Self.width - ifSelf.rect.left >Self.width: -Self.rect.right =0 - ifSelf.rect.bottom <0: -Self.rect.top =Self.height in ifSelf.rect.top >Self.height: -Self.rect.bottom =0 to + def collide_check (item,target): -Col_balls = [] the foreachinchTarget: *Distance = math.sqrt (Math.pow (item.rect.center[0]-each.rect.center[0]),2) + $Math.pow ((item.rect.center[1]-each.rect.center[1]),2))Panax Notoginseng ifDistance <= (item.rect.width + each.rect.width)/2: - col_balls.append (each) the returnCol_balls + A the def main (): + Pygame.init () - $Ball_image ='Gray_ball.png' $Bg_image ='Background.png' - -Bg_size = width, height =1024x768,681 theScreen =Pygame.display.set_mode (bg_size) -Pygame.display.set_caption ('my rolling ball-s.s')WuyiBackground =pygame.image.load (bg_image) #.convert_alpha the -Balls = [] Wu - About forIinchRange5): $Position = Random.randint (0, Width- -), Random.randint (0, Height- -) -Speed = [Random.randint (-Ten,Ten), Random.randint (-Ten,Ten)] -Ball =Ball (ball_image, Position, speed, bg_size) - whileCollide_check (ball,balls): ABall.rect.left, ball.rect.right = Random.randint (0, Width- -), Random.randint (0, Height- -) + balls.append (Ball) the - $Clock =Pygame.time.Clock () the therunning =True the the whileRunning: - for Event inchPygame.Event.Get(): in if Event. Type = =Pygame. QUIT: the sys.exit () the AboutScreen.blit (Background, (0,0)) the the foreachinchBalls: the Each.move () + screen.blit (Each.image, Each.rect) - the forIinchRange5):Bayiitem =Balls.pop (i) the ifCollide_check (item, balls): theitem.speed[0] =-item.speed[0] -item.speed[1] =-item.speed[1] - Balls.insert (i, item) the the Pygame.display.flip () the theClock.tick ( -) - the the if__name__ = ="__main__": theMain ()
Touch Method of Python-pygame