The Food class

Next, we will create the Food class (see 9.04_game_of_snake.py):

class Food:

def __init__(self, queue):
self.queue = queue
self.generate_food()

def generate_food(self):
x = random.randrange(5, 480, 10)
y = random.randrange(5, 295, 10)
self.position = (x, y)
rectangle_position = (x - 5, y - 5, x + 5, y + 5)
self.queue.put({'food': rectangle_position})

The description of the code is as follows:

  • Because we want to process all data centrally from within a queue, we pass the queue as an argument to the __init__ method of the Food class.
  • The __init__ method calls another method called generate_food, which is responsible for generating the snake food at random positions on the canvas.
  • The generate_food method generates a random (x, y) position on the canvas. However, because the place where the coordinates coincide is just a small point on the canvas, it would be barely visible. We, therefore, generate an expanded coordinate (rectangle_position ) ranging from five values less than the (x, y) coordinate up to five values higher than the same coordinate. Using this range, we can create a small rectangle on the canvas that would be easily visible and would represent our food.
  • However, we do not create the rectangle here. Instead, we pass the coordinates for the food (rectangle) into our queue using queue.put.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.75.217