Snake Game in Python Tutorial with pygame 🐍 (OOP)

Поделиться
HTML-код
  • Опубликовано: 2 дек 2024

Комментарии • 32

  • @programmingwithnick
    @programmingwithnick  Год назад +3

    I hope you took away lots from this video. Let me know below!
    PS: I created a course named "Object Oriented Programming Made Easy"! Sign up at bit.ly/3NaMfg4. I think you will enjoy it!

  • @ЕвгенийЗайченко-ц1р

    Thank you for this tutorial. I found it useful and clear for beginners. Following your tutorial, I wrote my first game. Not too simple, not too difficult. The golden average of complexity with nice comments. Thank you.

  • @lawrencejonesdesign
    @lawrencejonesdesign Год назад

    Nick, this was great. Thanks for helping me better understand Pygame and OOP!

    • @programmingwithnick
      @programmingwithnick  Год назад

      Wow, thank you very much!! I am glad my video was helpful. Your supports really helps!

  • @pariskgabo2130
    @pariskgabo2130 9 месяцев назад +1

    This is the best RUclips channel for beginners🎉

  • @jr-rcs
    @jr-rcs 9 месяцев назад

    I have just completed your tutorial and I want to Thank You a Lot... easy to follow, a lot to add to my new python brain and perfect for keeping experimenting.. Thanks a lot.

  • @Xarxes104
    @Xarxes104 Год назад

    This is by far the best tutorial for this type of content Ive seen so far on youtube. Im just randomly wanna see how other people code, it makes my mind relax after long hours of coding at work lmfao Ironic.

  • @manuelgarciagarcia2501
    @manuelgarciagarcia2501 Год назад +2

    Impressive tutorial, good visualization, good sound, excellent explanation that I have seen with subtitles in Spanish. And everything explained step by step, thank you very much for all the time invested in this wonderful tutorial, I am looking forward to seeing the next one. 👍

    • @programmingwithnick
      @programmingwithnick  Год назад +2

      Thank you very much for your feedback! I am glad that my work is helpful, it takes a great amount of time to produce these tutorials!

  • @moadhoueslati6838
    @moadhoueslati6838 Год назад +1

    Best tutorial out there, very underated content...

  • @ericleboullenger9348
    @ericleboullenger9348 11 месяцев назад

    Thank you Nick for your tutorial, clearly the best one on this topic one could find! You are a great teacher. Well done!

  • @andyryan4484
    @andyryan4484 2 месяца назад

    A great tutorial, I am planning to use this for my Digital Tech students as it is so clear and I feel I would be reinventing the wheel to try and make my own, I hope they send you many likes.

  • @Yun-gi7rc
    @Yun-gi7rc Год назад

    Thank you for making the subtitles.

  • @oldnight5337
    @oldnight5337 8 месяцев назад

    I just love your tutorials. You are great

  • @MNNocete
    @MNNocete 10 месяцев назад

    Very good tutorial. Thank you for sharing.

  • @iuliuS_o
    @iuliuS_o 10 месяцев назад

    BRO GOOD CONTENT❤I like your video DO PLEASE More video because its really good❤

  • @ChickenSandwich-vi8bz
    @ChickenSandwich-vi8bz Месяц назад

    I'm having trouble with this part:
    def check_collision_with_food(self):
    if self.snake.body[0] == self.food.position:
    self.food.position = self.food.generate_random_pos()
    I would run into the food and the food wouldn't do anything. I can't figure out why, I checked my spacing by instead of using tab I used four spaces, and my spacing was fine. I checked to see if anything was wrong in my problems tab, nothing. I checked my code and yours, they were identical. I don't know what is wrong with my code. My guess is it's a newer version of pygame that doesn't support this code anymore. Or I've discovered some bug in pygame.

  • @milesonwheels8127
    @milesonwheels8127 7 месяцев назад

    Hi. I am having position attribute error on line 17… food_rect =pygame.Rect(self.position.x*cell_size…) o don’t understand where this error is coming from. Position is a reference to self.position =vector2 (5,6)

    • @notsneazy2462
      @notsneazy2462 4 месяца назад

      supposed to be Vector2 (5,6) instead of vector2 (5,6)

  • @HalcGaming
    @HalcGaming Год назад

    Hi. Very nice tutorial.
    I noticed one thing. Lets say snake is moving to the right direction and if you press quickly down followed by left arrow then snake will change direction straight from right to left.
    Curious how would you fix that bug ?

    • @payalrajput7496
      @payalrajput7496 5 месяцев назад

      The solution is to introduce a queue to store the direction changes and process them one by one. This approach will ensure that the snake doesn't change direction immediately but rather processes each direction change in the order it was received.
      here is the updated code :
      import pygame, sys, random
      from pygame.math import Vector2
      pygame.init()
      title_font = pygame.font.Font(None, 60)
      score_font = pygame.font.Font(None, 40)
      GREEN = (173, 204, 96)
      DARK_GREEN = (43, 21, 54)
      OFFSET = 75
      cell_size = 30
      number_of_cell = 22
      food_surface = pygame.image.load(r"graphics/food.png")
      class Food():
      def __init__(self, snake_body):
      self.position = self.generate(snake_body)

      def draw(self):
      food_rect = pygame.Rect(OFFSET+self.position.x*cell_size, OFFSET+self.position.y*cell_size, cell_size, cell_size)
      screen.blit(food_surface, food_rect)

      def generate_random_cell(self):
      x = random.randint(0, number_of_cell-1)
      y = random.randint(0, number_of_cell-1)
      return Vector2(x, y)
      def generate(self, snake_body):
      position = self.generate_random_cell()
      while position in snake_body:
      position = self.generate_random_cell()
      return position

      class Snake():
      def __init__(self):
      self.body = [Vector2(6, 9), Vector2(5, 9), Vector2(4, 9)]
      self.direction = Vector2(1, 0)
      self.add_segment = False
      self.direction_queue = []
      self.eat_sound = pygame.mixer.Sound("sound/eat.mp3")
      self.wall_hit_sound = pygame.mixer.Sound("sound/wall.mp3")
      def draw(self):
      for segment in self.body:
      segment_rect = (OFFSET + segment.x * cell_size, OFFSET + segment.y * cell_size, cell_size, cell_size)
      pygame.draw.rect(screen, DARK_GREEN, segment_rect, 0, 7)
      def update(self):
      if self.direction_queue:
      new_direction = self.direction_queue.pop(0)
      if new_direction + self.direction != Vector2(0, 0):
      self.direction = new_direction
      self.body.insert(0, self.body[0] + self.direction)
      if not self.add_segment:
      self.body.pop()
      else:
      self.add_segment = False

      def reset(self):
      self.body = [Vector2(6, 9), Vector2(5, 9), Vector2(4, 9)]
      self.direction = Vector2(1, 0)
      self.direction_queue = []
      class Game():
      def __init__(self):
      self.snake = Snake()
      self.food = Food(self.snake.body)
      self.state = "RUNNING"
      self.score = 0
      def draw(self):
      self.food.draw()
      self.snake.draw()
      def update(self):
      if self.state == "RUNNING":
      self.snake.update()
      self.check_collision_with_food()
      self.check_collision_with_edge()
      self.check_collision_with_tail()
      def check_collision_with_food(self):
      if self.snake.body[0] == self.food.position:
      self.food.position = self.food.generate(self.snake.body)
      self.snake.add_segment = True
      self.score += 1
      self.snake.eat_sound.play()
      def check_collision_with_edge(self):
      if self.snake.body[0].x == number_of_cell or self.snake.body[0].x == -1:
      self.game_over()
      if self.snake.body[0].y == number_of_cell or self.snake.body[0].y == -1:
      self.game_over()

      def check_collision_with_tail(self):
      headless_body = self.snake.body[1:]
      if self.snake.body[0] in headless_body:
      self.game_over()
      def game_over(self):
      self.snake.reset()
      self.food.position = self.food.generate(self.snake.body)
      self.state = "STOPPED"
      self.score = 0
      self.snake.wall_hit_sound.play()
      screen = pygame.display.set_mode((2*OFFSET + cell_size * number_of_cell, 2*OFFSET + cell_size * number_of_cell))
      pygame.display.set_caption("Retro Snake")
      clock = pygame.time.Clock()
      game = Game()
      SNAKE_UPDATE = pygame.USEREVENT
      pygame.time.set_timer(SNAKE_UPDATE, 200)
      while True:
      for event in pygame.event.get():
      if event.type == SNAKE_UPDATE:
      game.update()
      if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
      if event.type == pygame.KEYDOWN:
      if game.state == "STOPPED":
      game.state = "RUNNING"
      if event.key == pygame.K_UP and game.snake.direction != Vector2(0, 1):
      game.snake.direction_queue.append(Vector2(0, -1))
      if event.key == pygame.K_DOWN and game.snake.direction != Vector2(0, -1):
      game.snake.direction_queue.append(Vector2(0, 1))
      if event.key == pygame.K_LEFT and game.snake.direction != Vector2(1, 0):
      game.snake.direction_queue.append(Vector2(-1, 0))
      if event.key == pygame.K_RIGHT and game.snake.direction != Vector2(-1, 0):
      game.snake.direction_queue.append(Vector2(1, 0))
      screen.fill(GREEN)
      pygame.draw.rect(screen, DARK_GREEN, (OFFSET-5, OFFSET-5, cell_size*number_of_cell+10, cell_size*number_of_cell+10), 5)
      game.draw()
      title_surface = title_font.render("Retro Snake", True, DARK_GREEN)
      score_surface = score_font.render(str(game.score), True, DARK_GREEN)
      screen.blit(title_surface, (OFFSET-5, 20))
      screen.blit(score_surface, (OFFSET+630, 20))
      pygame.display.update()
      clock.tick(60)

  • @rtester40
    @rtester40 9 месяцев назад

    I first want to TYVM for this tutorial. But I can't seem to get a game over text to appear I have it defined like we did the title and score but when game_over() no text appears I was trying to write GAME OVER then under it PRESS ANY KEY TO CONTINUE. also I tried to put some music so it not so quiet I got the music to play but it so loud you can;t hear the other 2 mp3's I tried the volume(0.1) but it did not seem to work it was still the same sound level as I never use that part of code
    could you maybe do an extra chapter for this game with what I was trying to implement?

    • @programmingwithnick
      @programmingwithnick  9 месяцев назад

      pygame does not work well with mp3s. Try converting your sound files to .ogg to see if that helps.

  • @Darkomen2003
    @Darkomen2003 Год назад +1

    So, new position of food is simply random? It's ok in the, lets say, first half of the game. But when snake will grow really long, what then? Imagine the situation when snake is 615 tiles long and there is only 10 free blocks. For how long program will hang on the function food.generate_random_pos? And it will be worse with each eaten food.

    • @programmingwithnick
      @programmingwithnick  Год назад

      Hello you are right. This solution is not the fastest but it is the easiest. In worst case schenario, the while loop will take around 1ms, so it won't be noticeable don't worry. We update the snake's position every 200ms for comparison. Of course you are free to use a more elegant solution.

  • @notsneazy2462
    @notsneazy2462 4 месяца назад

    An amazing tutorial, very useful. But I was running into a problem detecting collision between the food and the snake.
    This is my code:
    # Update Function- updates the game
    def update(self):
    self.snake.update()
    self.check_collision_with_food()
    # Collisions / eating
    def check_collision_with_food(self):
    if self.snake.body[0] == self.food.position:
    self.food.position = self.food.generate_random_pos()
    when the snake would "eat" the food it wouldnt do anything. the snake will just hover over the food and not eat it. pls help!!!

    • @ChickenSandwich-vi8bz
      @ChickenSandwich-vi8bz Месяц назад

      I'm having the same problem, I thought at first that maybe I was spacing my lines wrong but I was wrong.

    • @ChickenSandwich-vi8bz
      @ChickenSandwich-vi8bz Месяц назад

      My geuss is that its a new crappy pygame update. you might have to download a specific version of pygame that this dude is using.

  • @fatimashoaib8560
    @fatimashoaib8560 11 месяцев назад

    How can i downlaod the same image of food as yours?

  • @dlsantos1979
    @dlsantos1979 Месяц назад

    Consegui!!!!!!!!!!!!!!!!!!!!!!😀😀😀😀😀