马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 猪猪虾 于 2020-4-25 12:20 编辑
报错:TypeError: collide_check() takes 2 positional arguments but 5 were given
#cartoon
import pygame
import sys #退出程序时要用
from pygame.locals import *
from random import *
import math
#继承本身自带的类即可,本身定义了精灵
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 #希望球在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.right <0: #球出右边
self.rect.left = self.width
if self.rect.left >self.width:
self.rect.right = 0
if self.rect.bottom <0:
self.rect.top = self.height
if self.rect.top > self.height:
self.rect.bottom = 0
#target是除了Item(1个球),的四个球
def collide_check(item,target):
collide_ball = []
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:
collide_ball.append(each)
return collide_ball
def main():
pygame.init()
ball_image = "gray_ball.png"
bg_image = "background_ball.png"
running = True
bg_size = width,height = 1024,681
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("play the ball")
balls= []
#产生五个随机大小相同的球
for i in range(5):
position = randint(0,width-100),randint(0,height-100) #球宽是100,避免球越界
speed = [randint(-10,10),randint(-10,10)]
ball = Ball(ball_image,position,speed,bg_size)
#如果产生的球发生碰撞,重新再设置球的位置
while collide_check(ball,balls):
ball.rect.left,ball.rect.top = randint(0,width-100),randint(0,height-100)
balls.append(ball)
clock = pygame.time.Clock()
background =pygame.image.load(bg_image).convert_alpha()
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 i in range(5):
item = balls.pop(i)
if collide_check(item,balls): #collide_ball不为空
item.speed[0] = -item.speed[0]
item.speed[1] = -item.speed[1]
balls.insert(i,item)
collide_check(item,balls)
pygame.display.flip()
clock.tick(30)
if __name__ =="__main__":
main()
|