Reputation: 309
In this program, I want a bigger movable circle and many multi-colored smaller circles. However, when I run the program all of the smaller circles are all the same color and I cannot figure out how to randomly give each of them a different color. How do I fix this?
import pygame as pg
import random as rd
pg.init()
screen = pg.display.set_mode((800, 600))
p_1_x = 200
p_1_y = 200
p_1_change_x = 0
def p_1(x, y):
player_1 = pg.draw.circle(screen, (2, 2, 0), (x, y), 15)
locations = []
small_color = []
for i in range(50):
red = rd.randint(0, 220)
blue = rd.randint(0, 220)
green = rd.randint(0, 220)
x = rd.randint(100, 700)
y = rd.randint(100, 500)
locations.append((x, y))
small_color.append((red, blue, green))
while True:
screen.fill((255, 255, 255))
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
p_1_change_x = 1
if event.key == pg.K_LEFT:
p_1_change_x = -1
if event.type == pg.KEYUP:
if event.key == pg.K_RIGHT or pg.K_LEFT:
p_1_change_x = 0
p_1_x += p_1_change_x
p_1(p_1_x, p_1_y)
for locate in locations:
pg.draw.circle(screen, (small_color[i]), locate, 5)
pg.display.update()
Upvotes: 0
Views: 1052
Reputation: 1985
be sure you import random
library at the first line:
import random as rd
Here is a simple function, which generate random color:
def random_color():
r = rd.randint(0, 255)
g = rd.randint(0, 255)
b = rd.randint(0, 255)
return (r, g, b)
so you can call it when ever you need to:
color = random_color()
draw.circle(screen, color, (x, y), SIZE)
I make a repo in the GitHub and did some changes, Dots are colorful, new dot gets random color and the ball gets bigger whenever eats a dot.
https://github.com/peymanmajidi/Ball-And-Dots-Game__Pygame
Upvotes: 0
Reputation: 11342
In the main loop, you're using i
which never changes. Use enumerate to return an index while looping through the locations collection.
Try this code:
for i,locate in enumerate(locations):
pg.draw.circle(screen, (small_color[i]), locate, 5)
Upvotes: 2