python - Can anyone explain to me how this code allows the stars to move? -


trying understand how code works, can explain please.

def draw_star(star): # drawing star     # need change pixel, use set_at, not draw.line     screen.set_at((star[0], star[1]), (255, 255, 255))     star[0] -= 1     if star[0] < 0:         star[0] = screen.get_width()         star[1] = random.randint(0, screen.get_height())  stars = [] in range(1200):     x = random.randint(0, screen.get_width())     y = random.randint(0, screen.get_height())     stars.append([x,y])  star in stars:     draw_star(star) 

first, code generates 1200 [x, y] coordinates, each python list:

stars = [] in range(1200):     x = random.randint(0, screen.get_width())     y = random.randint(0, screen.get_height())     stars.append([x,y]) 

each x , y coordinate consist of random value within constraints of screen.

next, each of these coordinates drawn:

for star in stars:     draw_star(star) 

this passes [x, y] coordinate list function draw_star

def draw_star(star): # drawing star 

this sets white pixel @ given coordinates (star[0] x, star[1] y coordinate):

    # need change pixel, use set_at, not draw.line     screen.set_at((star[0], star[1]), (255, 255, 255)) 

the code subtracts 1 x coordinate (one step left). changes original list, because mutable lists used:

    star[0] -= 1 

if changed coordinates beyond edge of screen, star coordinates replaced new coordinates on right-hand side of screen, @ random height:

    if star[0] < 0:         star[0] = screen.get_width()         star[1] = random.randint(0, screen.get_height()) 

if repeat for star in stars: draw_star(star) loop screen blanking in between, you'd animating stars moving right left, new stars appearing on right @ random heights stars drop off left-hand side of screen.

the core idea here draw_star() function handles mutable lists , changes values contained in them, changing contents of global stars list next loop of animation.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -