I made a Snake game with the help of Angela Wu's 100 days of Coding Python course on Udemy. Every time the "food" gets eaten, the snake gets longer. So far so good.
I changed the color of the new food to a random color using the function make_color in food.py:
def make_color(self):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
random_color = r, g, b
return random_color
In the following method, where the new snake segment gets created, I called this method:
def refresh(self):
self.setheading(random.randint(0, 360))
self.color(self.make_color())
random_x = random.randint(-280, 280)
random_y = random.randint(-280, 280)
self.goto(random_x, random_y)
Both are inside the Food class.
So now every new food has a random color, as desired.
When the food gets eaten, the snake gains another segment; this is handled in snake.py inside the Snake class:
def add_segment(self, position):
new_segment = Turtle(shape="square")
new_segment.color(255, 255, 255)
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)
This works totally fine, the new segment is white since I used 255, 255, 255. But I want it to have the same random color as the food it just ate. And I just can't get it to work.
I guess I need to use the random_color variable from food.py but I can't figure out how. food is imported in the snake.py via from food import Food