Stack Overflow Asked by user14050624 on December 16, 2020
I’m trying to generate a random number between 1 and 3 for each snowflake, and the snowflake is moved down one pixel.
I am not sure how to do this because I’m really a beginner with pygame
. I have tried it with a for
loop before the while
loop.
The code currently flickers different colors. Instead, it should just re-color the ‘snowflakes’.
import pygame
import random
# Initialize the game engine
pygame.init()
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
GREEN = [0, 255, 0]
RED = [255, 0, 0]
colourList = [BLACK, WHITE, GREEN, RED]
colour = random.choice(colourList)
# Set the height and width of the screen
SIZE = [400, 400]
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Snow Animation")
clock = pygame.time.Clock()
# Create an empty list
snow_list = []
# Loop 100 times and add a snow flake in a random x,y position
for i in range(100):
x = random.randrange(0, 400)
y = random.randrange(0, 400)
snow_list.append((WHITE, [x, y]))
def recolour_snowflake(snowflake):
color = [random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)]
return [color, snowflake[1]]
count = 0
# Loop until the user clicks the close button.
done = False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# change the color of snow flakes
if count % 5 == 0:
snow_list = list(map(recolour_snowflake, snow_list))
count += 1
# Set the screen background
screen.fill(BLACK)
# Process each snow flake in the list
for i in range(len(snow_list)):
# Draw the snow flake
pygame.draw.circle(screen, snow_list[i][0], snow_list[i][1], 3)
# Move the snow flake down one pixel
snow_list[i][1][0] += 1
# If the snow flake has moved off the bottom of the screen
if snow_list[i][1][0] > 400:
# Reset it just above the top
y = random.randrange(-50, -10)
snow_list[i][1][1] = y
# Give it a new x position
x = random.randrange(0, 400)
snow_list[i][1][0] = x
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(20)
You can use random
to generate numbers in any particulate range. Here is the full code:
import random
for j in range(420):
print(random.randint(1,3))
This will print 420 lines with a number that is either 1, 2 or 3.
Answered by user10285006 on December 16, 2020
You can have the random module help you with generating random integers between 1 and 3 like this:
import random
random.randint(1,4)
Answered by Seyi Daniel on December 16, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP