Reputation: 577
I'm not well versed in Python so perhaps I'm missing something obvious but I don't understand why the code I'm using to generate random numbers appears to be using the same number every cycle. I'll go through my python code below, first it some basic imports and class setup stuff:
import random
class Static:
# Settings (some shoudl be, you know, settings settings)
PIXEL_COUNT = 144
current_pixels = [[0,0,0]]*144
target_pixels = [[255,255,255]]*144
# Output bar
def bar(self,settings):
# this is where the final output pixels will go
pixels = [(0,0,0)]*self.PIXEL_COUNT
for pixel_index in range(self.PIXEL_COUNT):
self.update_pixel(pixel_index)
# Debug
print('Update current_pixels',self.current_pixels);
for pixel_index in range(self.PIXEL_COUNT):
pixels[pixel_index] = (self.current_pixels[pixel_index][0],self.current_pixels[pixel_index][1],self.current_pixels[pixel_index][2])
return pixels
# Will process the pixel and the specified index
def update_pixel(self,index):
rand = random.randint(0,255)
for color in range(3):
if self.current_pixels[index][color] > self.target_pixels[index][color]:
self.current_pixels[index][color] -= 1
elif self.current_pixels[index][color] < self.target_pixels[index][color]:
self.current_pixels[index][color] += 1
else:
self.current_pixels[index][color] = rand
_inst = Static()
bar = _inst.bar
bar({})
I'd be happy to put the code in a fiddle if anybody has one that isn't going to make me sign up to use it. When I run that code I get an output to the terminal of a list containing 144 lists containing the same number (all numbers across all lists are the same). As I understand the code it should have a bunch of different values (and only the values in a list pixel list should match - going for a white static thing). Like I said I'm pretty new to python so it's probably something basic but I don't have any idea what it could be. Any help?
Upvotes: 0
Views: 383
Reputation: 588
your problem is your if else
block.
if self.current_pixels[index][color] > self.target_pixels[index][color]:
self.current_pixels[index][color] -= 1
elif self.current_pixels[index][color] < self.target_pixels[index][color]:
self.current_pixels[index][color] += 1
else:
self.current_pixels[index][color] = rand
This code would never reach the else
unless the current_pixels
element is equal to its target_pixels
equivalent. Since every current_pixels
element is initialized as 0, and every target_pixels
element starts at 255, you simply trigger the elif
block, meaning you increment all the RGB values by 1.
I'm not sure of your end goal here, but if you just wanted current_pixels
to be initialized to random values between 0 and 255, you can do that with a nested list comprehension as a one-liner.
Just replace
current_pixels = [[0,0,0]]*144
with
current_pixels = [[random.randint(0,255) for _ in range(3)] for _ in range(144)]
Upvotes: 2