The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

This topic is READ ONLY
ZhangXunqi (8) [Avatar] Offline
#1
Hi!Chapter 17 is really difficult...
In example 17.2
why the last 'for' loop in 'while' loop can let 9 balls run at the same time?
I think every loop is alone,why doesn't the code let the ball run one by one?
And I haven't seen location change ,I mean :ball.rect.left+speed[0] or ball.rect.top+speed[1]
Does sprite work out them?
The following is the code:
import sys,pygame
from random import *

class MyBallClass(pygame.sprite.Sprite):
def __init__(self,image_file,location,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load(image_file)
self.rect=self.image.get_rect()
self.rect.left,self.rect.top=location
self.speed=speed

def move(self):
self.rect=self.rect.move(self.speed)
if self.rect.left<0 or self.rect.right>width:
self.speed[0]=-self.speed[0]
if self.rect.top<0 or self.rect.bottom>height:
self.speed[1]=-self.speed[1]

size=width,height=640,480
screen=pygame.display.set_mode(size)
screen.fill([255,255,255])
img_file="beach_ball.png"
balls=[]
for row in range (0,3):
for column in range(0,3):
location=[column*180+10,row*180+10]
speed=[choice([-2,2]),choice([-2,2])]
ball=MyBallClass(img_file,location,speed)
balls.append(ball)
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:sys.exit()
pygame.time.delay(20)
screen.fill([255,255,255])
for ball in balls:
ball.move()
screen.blit(ball.image,ball.rect)
pygame.display.flip()




THANKS