|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pygame
import sys
import math
from pygame.locals import *
from random 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[0], bg_size[1]
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > self.width:
self.speed[0] = -self.speed[0]
elif self.rect.top < 0 or self.rect.bottom > self.height:
self.speed[1] = -self.speed[1]
def collide_check(item, target):
col_balls = []
for each in target:
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))
if distance <= (item.rect.width + each.rect.width) / 2:
col_balls.append(each)
return col_balls
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 - FishC Demo')
background = pygame.image.load(bg_image).convert_alpha()
balls = []
BALL_NUM = 5
for i in range(BALL_NUM):
position = randint(0, width-100), randint(0, height-100)
speed = [randint(-10, 10), randint(-10, 10)]
ball = Ball(ball_image, position, speed, bg_size)
balls.append(ball)
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(background, (0, 0))
for each in balls:
each.move()
screen.blit(each.image, each.rect)
for i in range(BALL_NUM):
item = balls.pop(i)
if collide_check(item, balls):
item.speed[0] = -item.speed[0]
item.speed[1] = -item.speed[1]
balls.insert(i, item)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
------------------------------------------
Windows 10 专业版 | Python 3.7.6
------------------------------------------
【我的问题】
1、为何自定义的move()函数有缩进,而collide_check()函数不需要缩进?
是不是因为move()函数是球基类的属性,而collide_check()函数则不属于,所以一个需要缩进在基类里,而另一个则不需要?
2、self.width, self.height = bg_size[0], bg_size[1] 没看懂,是不是可以拆分成self.width = bg_size[0],self.height = bg_size[1]?
******************************
感谢大神不吝赐教,为新手解疑释惑。
赠人玫瑰,手有余香,好人一生平安!
1.move(self)是类的方法,要基于类的缩进。
2.是的,可以拆分。
|
|