Friday April 17, 2026

This Free Friday I am working on a project on YouTube a Snake Game part 2.

 class MAIN:
    def __init__(self):
        self.snake = SNAKE()
        self.fruit = FRUIT()

    def update(self):
        self.snake.move_snake()

    def draw_elements(self):
            self.fruit.draw_fruit()
            self.snake.draw_fruit()

    def check_collisiion(self):
        if self.fruit.pos == self.snake.body[0]:
            self.fruit.randomize()
            self.snake.add_block()
  • This is a third class called main it will contain the entire game logic and the snake and fruit object.
class FRUIT:
  def __init__(self):
        self.randomize()

  def draw_fruit(self):
      fruit_rect = pygame.Rect(int(self.pos.x * cell_size),int(self.pos.y * cell_size),cell_size,cell_size)
      pygame.draw.rect(screen,(126,166,114),fruit_rect)

  def randomize(self):
      self.x = random.randint(0,cell_number - 1)
      self.y = random.randint(10,cell_number - 1)
      self.pos = Vector2(self.x,self.y)
      
  • This is a more updated code of the class fruit.
class SNAKE:
    def __init__(self):
        self.body = [Vector2(5,10), Vector2(6,10), Vector2(7,10)]
        self.direction = Vector2(1,0)
        self.new_block = False

    def draw_snake(self):
        for block in self.body:
            x_pos -=int(block.x * cell_size)
            y_pos -= int(block.y * cell_size)
            block_rect = pygame.rect(x_pos,y_pos,cell_size,cell_size)
            pygame.draw.rect(screen,(183,191,122),block_rect)

    def move_snake(self):
        if self.new_block == True:
            body_copy = self.body[:]
            body_copy.insert(0,body_copy[0] + self.direction)
            self.body = body_copy[:]
            self.new_block = False
        else:
            body_copy = self.body[:-1]
            body_copy.insert(0,body_copy[0] + self.direction)
            self.body = body_copy[:]

    def add_block(self):
        self.new_block = True
  • This is a more updated code of the class snake.
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
            if event.type == SCREEN_UPDATE:
                main_game.update()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    main_game.snake.direction = Vector2(0,-1)
                if event.key == pygame.K_RIGHT:
                    main_game.snake.direction = Vector2(1,0)
                if event.key == pygame.K_DOWN:
                    main_game.snake.direction = Vector2(0,1)
                if event.key == pygame.K_LEFT:
                    main_game.snake.direction = Vector2(-1,0)
  • This part of the code is for the snake to move up, down and right, to left.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top