Snake Game in Python Tutorial with pygame 🐍 (OOP)

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ก.ย. 2024

ความคิดเห็น • 27

  • @programmingwithnick
    @programmingwithnick  ปีที่แล้ว +2

    I hope you took away lots from this video. Let me know below!
    PS: I'm creating an OOP course! Sign up at programmingwithnick.com/course for early access and a 50% launch discount.

  • @ЕвгенийЗайченко-ц1р
    @ЕвгенийЗайченко-ц1р ปีที่แล้ว +2

    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.

  • @andyryan4484
    @andyryan4484 3 วันที่ผ่านมา

    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.

  • @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!

  • @ericleboullenger9348
    @ericleboullenger9348 9 หลายเดือนก่อน

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

  • @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.

    • @programmingwithnick
      @programmingwithnick  ปีที่แล้ว

      Thank you very much for your kind words. It means a lot to me!

  • @jr-rcs
    @jr-rcs 7 หลายเดือนก่อน

    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.

  • @moadhoueslati6838
    @moadhoueslati6838 ปีที่แล้ว +1

    Best tutorial out there, very underated content...

  • @pariskgabo2130
    @pariskgabo2130 6 หลายเดือนก่อน +1

    This is the best TH-cam channel for beginners🎉

  • @lawrencejonesdesign
    @lawrencejonesdesign 10 หลายเดือนก่อน

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

    • @programmingwithnick
      @programmingwithnick  10 หลายเดือนก่อน

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

  • @Yun-gi7rc
    @Yun-gi7rc ปีที่แล้ว

    Thank you for making the subtitles.

  • @oldnight5337
    @oldnight5337 6 หลายเดือนก่อน

    I just love your tutorials. You are great

  • @MNNocete
    @MNNocete 8 หลายเดือนก่อน

    Very good tutorial. Thank you for sharing.

  • @iuliuS_o
    @iuliuS_o 8 หลายเดือนก่อน

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

  • @notsneazy2462
    @notsneazy2462 2 หลายเดือนก่อน

    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!!!

  • @rtester40
    @rtester40 7 หลายเดือนก่อน

    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  7 หลายเดือนก่อน

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

  • @milesonwheels8127
    @milesonwheels8127 4 หลายเดือนก่อน

    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 2 หลายเดือนก่อน

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

  • @HalcGaming
    @HalcGaming 10 หลายเดือนก่อน

    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 3 หลายเดือนก่อน

      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)

  • @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.

  • @fatimashoaib8560
    @fatimashoaib8560 9 หลายเดือนก่อน

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