copy() 问题
import pygameimport sys
import os
import math as m
os.chdir("C:\\Users\\david\\Desktop\\碰撞小球")
from random import *
from pygame.locals 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, 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 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 = []
for i in range(5):
position = randint(0, width - 100), randint(0, height - 100)
speed =
ball = Ball(ball_image, position, speed, bg_size)
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 eachball in balls:
ball_index = 0
item = balls.pop(ball_index)
for each in balls:
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:
each.speed, each.speed = - \
each.speed, -each.speed
item.speed, item.speed = - \
item.speed, -item.speed
balls = balls_copy#-----------------------------------------------对于这一行代码,为什么balls =balls_copy 与balls =balls_copy.copy(),两段代码执行的效果相差这么大??
for each in balls:
screen.blit(each.image,each.rect)
each.move()
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main() 对于这段代码中的 balls = balls_copy ,它的作用是将 balls_copy 的值赋给 balls 。这意味着 balls 和 balls_copy 指向同一个对象,任何对 balls 的修改都会影响到 balls_copy ,反之亦然。
而对于 balls = balls_copy.copy() ,它的作用是创建一个 balls_copy 的副本,并将副本的值赋给 balls 。这意味着 balls 和 balls_copy 指向不同的对象,它们之间的修改互不影响。
在这段代码中,如果使用 balls = balls_copy ,那么在后续的循环中对 balls 的修改也会影响到 balls_copy ,导致结果不符合预期。而如果使用 balls = balls_copy.copy() ,则可以保持 balls_copy 的原始值不变,从而得到正确的结果。 但 balls = balls_copy 这一行代码后并没有对balls的修改,而且在此之前已经有了balls_copy = balls.copy(),那为什么还会出现这样的问题
页:
[1]