pygame的列表问题
from pygame.locals import *from random import *
import pygame
import sys
import os
import math as m
os.chdir("C:\\Users\\david\\Desktop\\碰撞小球")
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, bg_size
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left > self.width:
self.rect.left = 0
elif self.rect.top > self.height:
self.rect.bottom = 0
elif self.rect.bottom < 0:
self.rect.top = self.height
elif self.rect.right < 0:
self.rect.left = self.width
def collide_check(item,target):
col_box = []
for each in target:
distance = m.sqrt(m.pow((item.rect.center - each.rect.center), 2) + m.pow(
(item.rect.center - each.rect.center), 2))
if distance <= (item.rect.width + each.rect.width) / 2:
col_box.append(each)
return col_box
def main():
pygame.init()
ball_image = "gray_ball.png"
bg_image = "background.png"
running = True
bg_size = width, height = 1024, 511
screen = pygame.display.set_mode(bg_size)
background = pygame.image.load(bg_image).convert_alpha()
pygame.display.set_caption("nihao")
balls_copy = []
balls = []
ball_number = 5
for i in range(5):
position = randint(0, width - 100), randint(0, height - 100)
speed =
ball = Ball(ball_image, position, speed, bg_size)
while collide_check(ball, balls): #------------------------------------------- 刚开始balls 不是空的吗,为什么执行collide_check(ball, balls)不会出错
ball.rect.left, ball.rect.top = randint(0, width-100), randint(0, width - 100)
balls.append(ball)
clock = pygame.time.Clock()
balls_copy = balls.copy()
while running:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
screen.blit(background, (0, 0))
for each in balls:
screen.blit(each.image, each.rect)
each.move()
for i in range(5):
item = balls.pop(i)
if collide_check(item, balls):
item.speed,item.speed = -item.speed,-item.speed
balls.insert(i, item)
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
问题描述:
在这段代码中,有一个问题是关于列表 balls 的。在创建 ball 对象并将其添加到 balls 列表之前,使用了 collide_check(ball, balls) 函数来检查是否与已存在的球发生碰撞。但是,在刚开始创建 balls 列表时,它是空的,为什么执行 collide_check(ball, balls) 不会出错呢?
解决方案:
在刚开始创建 balls 列表时,它是空的,因此 collide_check(ball, balls) 不会出错。这是因为在Python中,空列表也是一个可迭代对象。当传递一个空列表作为参数给 collide_check 函数时, for each in target 这个循环会直接跳过,不会执行循环体内的代码。因此,即使 balls 列表为空,也不会出现错误。
页:
[1]