Reputation: 57
In my game, I am trying to make it where a rectangle that is dropping has a randomly generated color in a list of three, and that every time a new rectangle is spawned, the color changes randomly to one of those three in the list. With the code I have now, it cycles very quickly between those three colors over and over again without stopping. I also want to figure out how to grab whatever color the block is and make adjacent blocks of the same color de-spawn, but I have had no luck trying to code that.
I have tried setting the color as a variable outside the while loop, but it only chooses the color randomly from the list once, and does not change again.
Upvotes: 1
Views: 516
Reputation: 210996
The list of rectangles is not sufficient. You need a list of colors, too.
colors = [red,green,blue]
colorChoice = random.choice(colors)
player = pygame.Rect(x,y,width,height)
copylist = []
colorList = []
Every time when a new block spawns, then a then current color has to be append to the color list and the current rectangle has to be append to the block list. Further a new random color has to be set.
Create a function which does the job and use a global
statement to set the variables in global scope:
def newBlock():
global player, copylist, colorList, colorChoice
copylist.append(player.copy())
colorList.append(colorChoice)
player.y = 50
colorChoice = random.choice(colors)
Call newBlock
to spawn a new block and draw ech block in its color:
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == moveDownEvent:
if player.y >= 390 or player.move(0, vel).collidelist(copylist) >= 0:
newBlock() # <--- spawn new block
else:
player.y += vel
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player.x > 168 and player.move(-vel, 0).collidelist(copylist) < 0:
player.x -= vel
if keys[pygame.K_RIGHT] and player.x < 330 and player.move(vel, 0).collidelist(copylist) < 0:
player.x += vel
if keys[pygame.K_DOWN] and player.y < 390:
if player.move(0, vel).collidelist(copylist) >= 0:
newBlock() # <--- spawn new block
else:
player.y += vel
win.fill((128,128,128))
pygame.draw.line(win,(0,0,0),(148,100),(148,410),2)
pygame.draw.line(win,(0,0,0),(350,100),(350,410),2)
pygame.draw.line(win,(0,0,0),(148,410),(350,410),2)
for i in range(len(copylist)):
pygame.draw.rect(win, colorList[i], copylist[i]) # <--- draw block with its color
pygame.draw.rect(win, colorChoice, player)
pygame.display.update()
clock.tick(24)
pygame.quit()
Upvotes: 1