Python snake game 🐍

แชร์
ฝัง
  • เผยแพร่เมื่อ 10 ก.พ. 2021
  • python snake game code tutorial example explained
    We're using Tkinter, because I have not taught PyGame at this point in time, in case you're wondering
    #python #snake #game
    Bro Code merch store 👟 :
    ===========================================================
    teespring.com/stores/bro-code-5
    ===========================================================
    music credits 🎼 :
    ===========================================================
    Up In My Jam (All Of A Sudden) by - Kubbi / kubbi
    Creative Commons - Attribution-ShareAlike 3.0 Unported- CC BY-SA 3.0
    Free Download / Stream: bit.ly/2JnDfCE
    Music promoted by Audio Library • Up In My Jam (All Of A...
    ===========================================================
    Twelve Speed by - Slynk
    • Video
    ===========================================================
  • วิทยาศาสตร์และเทคโนโลยี

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

  • @BroCodez
    @BroCodez  3 ปีที่แล้ว +441

    # **************************************
    # Python Snake
    # **************************************
    from tkinter import *
    import random
    GAME_WIDTH = 700
    GAME_HEIGHT = 700
    SPEED = 50
    SPACE_SIZE = 50
    BODY_PARTS = 3
    SNAKE_COLOR = "#00FF00"
    FOOD_COLOR = "#FF0000"
    BACKGROUND_COLOR = "#000000"
    class Snake:
    def __init__(self):
    self.body_size = BODY_PARTS
    self.coordinates = []
    self.squares = []
    for i in range(0, BODY_PARTS):
    self.coordinates.append([0, 0])
    for x, y in self.coordinates:
    square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
    self.squares.append(square)
    class Food:
    def __init__(self):
    x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
    y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE
    self.coordinates = [x, y]
    canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food")
    def next_turn(snake, food):
    x, y = snake.coordinates[0]
    if direction == "up":
    y -= SPACE_SIZE
    elif direction == "down":
    y += SPACE_SIZE
    elif direction == "left":
    x -= SPACE_SIZE
    elif direction == "right":
    x += SPACE_SIZE
    snake.coordinates.insert(0, (x, y))
    square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
    snake.squares.insert(0, square)
    if x == food.coordinates[0] and y == food.coordinates[1]:
    global score
    score += 1
    label.config(text="Score:{}".format(score))
    canvas.delete("food")
    food = Food()
    else:
    del snake.coordinates[-1]
    canvas.delete(snake.squares[-1])
    del snake.squares[-1]
    if check_collisions(snake):
    game_over()
    else:
    window.after(SPEED, next_turn, snake, food)
    def change_direction(new_direction):
    global direction
    if new_direction == 'left':
    if direction != 'right':
    direction = new_direction
    elif new_direction == 'right':
    if direction != 'left':
    direction = new_direction
    elif new_direction == 'up':
    if direction != 'down':
    direction = new_direction
    elif new_direction == 'down':
    if direction != 'up':
    direction = new_direction
    def check_collisions(snake):
    x, y = snake.coordinates[0]
    if x < 0 or x >= GAME_WIDTH:
    return True
    elif y < 0 or y >= GAME_HEIGHT:
    return True
    for body_part in snake.coordinates[1:]:
    if x == body_part[0] and y == body_part[1]:
    return True
    return False
    def game_over():
    canvas.delete(ALL)
    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
    font=('consolas',70), text="GAME OVER", fill="red", tag="gameover")
    window = Tk()
    window.title("Snake game")
    window.resizable(False, False)
    score = 0
    direction = 'down'
    label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
    label.pack()
    canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
    canvas.pack()
    window.update()
    window_width = window.winfo_width()
    window_height = window.winfo_height()
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = int((screen_width/2) - (window_width/2))
    y = int((screen_height/2) - (window_height/2))
    window.geometry(f"{window_width}x{window_height}+{x}+{y}")
    window.bind('', lambda event: change_direction('left'))
    window.bind('', lambda event: change_direction('right'))
    window.bind('', lambda event: change_direction('up'))
    window.bind('', lambda event: change_direction('down'))
    snake = Snake()
    food = Food()
    next_turn(snake, food)
    window.mainloop()

    • @koolaidlover2382
      @koolaidlover2382 3 ปีที่แล้ว +19

      Dude! You are a life saver!

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

      sup

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

      Thanks bro

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

      Sir is code ko copy kar sakte h?

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

      how can I pack all code so I can use it with other modules too..

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

    I love your videos. so easy to understand why a certain line of code is written thanks to how you've explain it and easy to follow. thanks man

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

    Your tutorials are very understandable.Ive been binging on your full 12 hour python course and im about to finish it.Thank u

    • @BEATSBYDNVN
      @BEATSBYDNVN ปีที่แล้ว +3

      Ik this is from a year ago but did you end up finishing it? Where are you now with your skills

    • @SaathwikKolla-ij6bz
      @SaathwikKolla-ij6bz ปีที่แล้ว +2

      hey

  • @chasengonzales85
    @chasengonzales85 ปีที่แล้ว +36

    Ran through this whole video several times. Opened up Pycharm and ran with it. It was super easy to follow, and I now have a new game to play with.

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

      past the full code in chat box fr me

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

      hi...iam facing issue, my snake is always moving not moving in any direction, in my code pls reply
      from tkinter import *
      import random
      GAME_WIDTH = 700
      GAME_HEIGHT =700
      SPEED = 50
      SPACE_SIZE = 50
      BODY_PARTS = 3
      SNAKE_COLOR = "#00FF00"
      FOOD_COLOR = "#FF0000"
      BACKGROUND_COLOR = "#000000"
      class Snake:
      def __init__(self):
      self.body_size = BODY_PARTS
      self.coordinates = []
      self.squares = []
      for i in range(0, BODY_PARTS):
      self.coordinates.append([0,0])
      for x,y in self.coordinates:
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y+ SPACE_SIZE, fill=SNAKE_COLOR, tag ="snake" )
      self.squares.append(square)
      class Food:
      def __init__(self):
      x = random.randint(0,(GAME_WIDTH/SPACE_SIZE)-1)* SPACE_SIZE
      y = random.randint(0,(GAME_HEIGHT/SPACE_SIZE)-1)* SPACE_SIZE

      self.coordinates = [x, y]
      canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag ="food")
      def next_turn(snake, food):
      x, y = snake.coordinates[0]
      if direction == 'up':
      y-= SPACE_SIZE
      elif direction == 'down':
      y+= SPACE_SIZE
      elif direction == 'left':
      x-= SPACE_SIZE
      elif direction == 'right':
      x+= SPACE_SIZE

      snake.coordinates.insert(0, (x, y))
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE,fill=SNAKE_COLOR )
      snake.squares.insert(0,square)
      if x == food.coordinates[0] and y == food.coordinates[1]:
      global score
      score += 1
      label.config(text = "Score:{}".format(score))
      canvas.delete("food")
      food = Food()
      else:
      del snake.coordinates[-1]

      canvas.delete(snake.squares[-1])
      del snake.squares[-1]

      window.after(SPEED, next_turn, snake, food)
      def change_direction(new_direction):

      global direction
      if new_direction == 'left':
      if direction != 'right':
      direction = new_direction
      elif new_direction == 'right':
      if direction != 'left':
      direction = new_direction
      elif new_direction == 'up':
      if direction != 'down':
      direction = new_direction
      elif new_direction == 'down':
      if direction != 'up':
      direction = new_direction
      def check_collision():
      pass
      def game_over():
      pass
      window = Tk()
      window.title("Snake game")
      window.resizable(False, False)
      score = 0
      direction = 'down'
      label = Label(window, text="Score:{}".format(score),font=('consolas',40))
      label.pack()
      canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT,width=GAME_WIDTH)
      canvas.pack()
      window.update()
      window_width = window.winfo_width()
      window_height = window.winfo_height()
      screen_width = window.winfo_screenwidth()
      screen_height = window.winfo_screenheight()
      x = int((screen_width/2) - (window_width/2))
      y = int((screen_height/2) - (window_height/2))
      window.geometry(f"{window_width}x{window_height}+{x}+{y}")
      window.bind('', lambda event: change_direction('left'))
      window.bind('', lambda event: change_direction('right'))
      window.bind('', lambda event: change_direction('up'))
      window.bind('', lambda event: change_direction('down'))
      snake = Snake()
      food = Food()
      next_turn(snake, food)
      window.mainloop()

  • @moukaloka9543
    @moukaloka9543 3 ปีที่แล้ว +125

    bro you are the TUTORIAL MASTER !!!

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

      Please help how to get the white game table on the game tkinter

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

      Output is stop only for 1second what to do

    • @Short.Vs_code
      @Short.Vs_code 4 หลายเดือนก่อน

      ​@@shaliniminz2743 same with me

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

    Either I'm finally starting to understand python, or you are just a very good teacher.

    • @sarangm3152
      @sarangm3152 ปีที่แล้ว +8

      He is a good teacher

    • @H3XED_OwO
      @H3XED_OwO 7 หลายเดือนก่อน +3

      probably both

  • @dan1locksk
    @dan1locksk ปีที่แล้ว +75

    If you want to make a restart buton not to rerun the code each time, here is how you can make it:
    create a restart function:
    def restart_game():
    global snake, food, score, direction
    # Reset game variables to initial values
    canvas.delete(ALL)
    snake = Snake()
    food = Food()
    score = 0
    direction = 'down'
    label.config(text="Score:{}".format(score))
    next_turn(snake, food)
    and add a restart button to the window:
    restart_button = Button(window, text="Restart", command=restart_game, font=('consolas', 20))
    restart_button.place(x=0, y=0)
    BTW, Thanks @Bro Code, watched you 12 hour tuturial, really usefull, making progress already

    • @goku5366
      @goku5366 ปีที่แล้ว +4

      been looking for this, thanks

    • @eklavya22k34
      @eklavya22k34 9 หลายเดือนก่อน +2

      class Food:
      def __init__(self):
      while True:
      x = random.randint(0, (GAME_WIDTH / SPACE_SIZE) - 1) * SPACE_SIZE
      y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE
      # Check if the new food coordinates overlap with the snake
      if (x, y) not in snake.coordinates:
      break
      self.coordinates = [x, y]
      canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food")
      *******
      code, so that food is within win size and not overlap.

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

      how is it going so far? are you making any progress?

    • @dungvuong7201
      @dungvuong7201 8 หลายเดือนก่อน +2

      @@eklavya22k34
      I also encountered the same situation. But I coded according to yours and got an error

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

      Im geting positional arguments follow keyword arguments. Why is that and how to fix it?

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

    Thank you, sir, Good project with a good explanation.

  • @Balkac
    @Balkac 3 ปีที่แล้ว +6

    Well spent 30 minutes of Saturday morning! :) Great job, I would like to code this error-less way too ;)

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

    Thank you for this amazing series! Getting myself started in learning programming :)

    • @stivenkasa8080
      @stivenkasa8080 2 ปีที่แล้ว

      Please help how to get the white game table on the game tkinter

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

      @@stivenkasa8080 bg='white' or BACKGROUND_COLOR='white'

  • @fasena71
    @fasena71 ปีที่แล้ว +5

    I think that you have to write False twice because it means window width and height , two values . Very good tutorial

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

    Thanks for taking the time to put all this on the internet for all of us to look at free. Very awesome

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

    nice simple game tutorial Bro.. Thank you so much for this tutorial..

  • @eklavya22k34
    @eklavya22k34 9 หลายเดือนก่อน +3

    Thanks u v much, run my first GUI based game, loved it.
    Ur knowledge of subj is v good, u teach as evth is a piece of cake. Additionaly, ur voice is like a robot, consistent and soothing to hear.
    Ur videos are begginer friendly, i will finish as many i can.
    Thanks for sharing ur knowledge with us and making us better coder.
    Stay safe. Keep progressing in right direction.

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

      hi...iam facing issue, my snake is always moving not moving in any direction, in my code pls reply
      from tkinter import *
      import random
      GAME_WIDTH = 700
      GAME_HEIGHT =700
      SPEED = 50
      SPACE_SIZE = 50
      BODY_PARTS = 3
      SNAKE_COLOR = "#00FF00"
      FOOD_COLOR = "#FF0000"
      BACKGROUND_COLOR = "#000000"
      class Snake:
      def __init__(self):
      self.body_size = BODY_PARTS
      self.coordinates = []
      self.squares = []
      for i in range(0, BODY_PARTS):
      self.coordinates.append([0,0])
      for x,y in self.coordinates:
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y+ SPACE_SIZE, fill=SNAKE_COLOR, tag ="snake" )
      self.squares.append(square)
      class Food:
      def __init__(self):
      x = random.randint(0,(GAME_WIDTH/SPACE_SIZE)-1)* SPACE_SIZE
      y = random.randint(0,(GAME_HEIGHT/SPACE_SIZE)-1)* SPACE_SIZE

      self.coordinates = [x, y]
      canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag ="food")
      def next_turn(snake, food):
      x, y = snake.coordinates[0]
      if direction == 'up':
      y-= SPACE_SIZE
      elif direction == 'down':
      y+= SPACE_SIZE
      elif direction == 'left':
      x-= SPACE_SIZE
      elif direction == 'right':
      x+= SPACE_SIZE

      snake.coordinates.insert(0, (x, y))
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE,fill=SNAKE_COLOR )
      snake.squares.insert(0,square)
      if x == food.coordinates[0] and y == food.coordinates[1]:
      global score
      score += 1
      label.config(text = "Score:{}".format(score))
      canvas.delete("food")
      food = Food()
      else:
      del snake.coordinates[-1]

      canvas.delete(snake.squares[-1])
      del snake.squares[-1]

      window.after(SPEED, next_turn, snake, food)
      def change_direction(new_direction):

      global direction
      if new_direction == 'left':
      if direction != 'right':
      direction = new_direction
      elif new_direction == 'right':
      if direction != 'left':
      direction = new_direction
      elif new_direction == 'up':
      if direction != 'down':
      direction = new_direction
      elif new_direction == 'down':
      if direction != 'up':
      direction = new_direction
      def check_collision():
      pass
      def game_over():
      pass
      window = Tk()
      window.title("Snake game")
      window.resizable(False, False)
      score = 0
      direction = 'down'
      label = Label(window, text="Score:{}".format(score),font=('consolas',40))
      label.pack()
      canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT,width=GAME_WIDTH)
      canvas.pack()
      window.update()
      window_width = window.winfo_width()
      window_height = window.winfo_height()
      screen_width = window.winfo_screenwidth()
      screen_height = window.winfo_screenheight()
      x = int((screen_width/2) - (window_width/2))
      y = int((screen_height/2) - (window_height/2))
      window.geometry(f"{window_width}x{window_height}+{x}+{y}")
      window.bind('', lambda event: change_direction('left'))
      window.bind('', lambda event: change_direction('right'))
      window.bind('', lambda event: change_direction('up'))
      window.bind('', lambda event: change_direction('down'))
      snake = Snake()
      food = Food()
      next_turn(snake, food)
      window.mainloop()

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

    Great job! One day I'll be programming like you! =] Thanks for sharing this programming lesson. One more subscriber.

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

    Very cool and instructional. Thanks Bro!!

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

    hey bro thanks for the tutorial it really helped me. This was my first gaming project I have done and I'm really satisfied. Python snake game 🐍..... (I subscribed :) )

  • @JDgiggles
    @JDgiggles 11 หลายเดือนก่อน +1

    Thank you for this. I'm really excited to learn and develop my coding skills

  • @kyablonska95
    @kyablonska95 8 หลายเดือนก่อน +1

    thanks a lot for sharing it! you are helping to make learning python more fun and enjoyable :)

  • @Gunsi-kb2xq
    @Gunsi-kb2xq ปีที่แล้ว +9

    Great Tutorial.. I will implement the following by myself > Highscore System and "Food spawn in Body check". Also, there is a problem with the code. Windows Geometry expects inters and as the code is, there will be a problem if dividing by SPACEequals to 0.5... what I did in the end was just add the int to x and y. If you
    x = int((screen_width / 2) - (window_width / 2))
    y = int((screen_height / 2) - (window_height / 2))
    window.geometry(f"{window_width}x{window_height}+{x}+{y}")

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

      hey did you figure out how to implement the high score system? because i can't figure it out.

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

      BRO THANKS, YOU SAVED ME SO MUCH TIME

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

    i am so happy i have searches the whole for a tutorial to make a game using python

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

    These codes are really understandble, i did same thing with you while getting what you're saying

  • @prakharposwal9
    @prakharposwal9 3 ปีที่แล้ว +3

    you are a really good teacher

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

    Thanks man i appriciate you efforts 👍👍it amazing tutrorial it helped me a lottt .... I expect more tutorials😊😊

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

    Thanks for the lesson! It was harder to fully understand than the previous projects, but the result is much more enjoyable:) And there is a lot of space to customize the game and to practice the previous topics - adding customization buttons (colours, space size etc), various speed tweaks etc. For example, here I added the auto-incrementing of the snake speed:
    if x == food.coordinates[0] and y == food.coordinates[1]:
    global score
    global speed
    score += 1
    if speed > 60: speed -= 1
    score_label.config(text='Score: {}'.format(score))
    canvas.delete('food')
    food = Food()
    A small note - there is a "suicide" issue (when the direction is changed too fast, i.e. snake is moving down and if you click left and then instantly up (without allowing the snake to move left), the snake will eat itself. To fix this, I changed the key bindings to set a variable instead of calling a function:
    new_direction = StringVar(window)
    new_direction.set('down')
    window.bind("", lambda x:new_direction.set('up'))
    window.bind("", lambda x:new_direction.set('left'))
    window.bind("", lambda x:new_direction.set('down'))
    window.bind("", lambda x:new_direction.set('right'))
    window.bind("", lambda x:new_direction.set('up'))
    window.bind("", lambda x:new_direction.set('left'))
    window.bind("", lambda x:new_direction.set('down'))
    window.bind("", lambda x:new_direction.set('right'))
    After that, I added a check to the main function to see if a new direction is different from the current direction:
    global direction
    global new_direction
    # Change the direction of the snake
    if new_direction.get() == 'up' and direction != 'down': direction = 'up'
    if new_direction.get() == 'down' and direction != 'up': direction = 'down'
    if new_direction.get() == 'left' and direction != 'right': direction = 'left'
    if new_direction.get() == 'right' and direction != 'left': direction = 'right'
    This check is performed before everything, and this allows to change the snake direction only once per main function tick

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

      what if I would like to make the food will not land on the body of the snake (every block after the head of the snake)??

    • @sroouchiam
      @sroouchiam 2 ปีที่แล้ว

      hi may i know how to solve the "NameError : name 'speed' is not defined? I'm trying to increase the speed but it shows this statement

    • @noxzy1087
      @noxzy1087 2 ปีที่แล้ว

      hey, can you tell us more about other improvements you did to the code ?

    • @ahsanzizan
      @ahsanzizan 2 ปีที่แล้ว

      @@sroouchiam check your variable name(ikr 6 months late)

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

      if i wanted to put a restart button when there's the "GAME OVER" text , how do you recommend i do it?

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

    Bro u are tutorial master!!! U gave me ideas to make my final project for my python class !!!!!

  • @mdshishir6080
    @mdshishir6080 2 ปีที่แล้ว

    Completely done!!!!!!!
    Thank you Sir

  • @user-sc4mn9su7o
    @user-sc4mn9su7o 2 ปีที่แล้ว

    Nice!👍 A quick and easy snek game.

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

    you are amaaaaaaazing !!!
    i hope you make a series about kivy library and the other important libraries

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

    i've made this game by this video! thank you from japan!

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

    great course for beginners

  • @informatique-ham
    @informatique-ham 14 วันที่ผ่านมา

    nice and good explanAtion. Thanks

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

    for collosion detection you could just turn the squares list into a set and check if its smaller than the original list

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

    At 5:50 why did we add window.update() line after packing label and canvas, is it nesscessary?
    And why don't we create the label and canvas after setting the window size and position to be at the center?

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

    Thank you so much, this really helps. Now my teacher would be really happy watching this . we made indicator before a s our FOAE project now this really looks cool!!😁

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

    thanks for the step by step tutorial

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

    Nice game maker tutorial bro, i did it on live stream, it was awesome

  • @nuonduch585
    @nuonduch585 2 ปีที่แล้ว

    Hey bro 19/11/21 I finish your python tutorial beginning .Thanks Thanks you so much

  • @manhnguyenminh9730
    @manhnguyenminh9730 3 ปีที่แล้ว +3

    Thank you so much

  • @lolski-sr4yy
    @lolski-sr4yy 2 หลายเดือนก่อน +4

    Seems like I found a very minor flaw within the x/y part of the class Food: section. I don't know if its just idle being idle and is not working properly for reasons beyond me or just a new update thing, but x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE and y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE)-1) * SPACE_SIZE doesn't seem to function and will cause a "TypeError: 'float' object cannot be interpreted as an integer" unless you replace the / in the code with a //
    ie: x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1 bad, no good. x = random.randint(0, (GAME_WIDTH // SPACE_SIZE)-1 good, python likey.
    This isn't meant to discredit your code btw @BroCodez, just giving a heads up for anyone experiencing the same troubles I'm currently facing.
    edit: forgot to replace the // with a / on all of the bad codes lel

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

      THANK YOU SO MUCH DUDE I WAS HAVING THE SAME PROBLEM ITS FIXED NOW

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

      THANKS A LOTT BROOO!!! I WAS LITERALLY STRUGGLING SINCE YESTERDAY!!

    • @kailenbains4418
      @kailenbains4418 28 วันที่ผ่านมา

      THANK YOU!!

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

    This was really helpful, Thank you!

  • @HoisinDuckWrap
    @HoisinDuckWrap 5 หลายเดือนก่อน

    Is there anyway to make a main menu in tkinter? I want to make this game but with a main menu, not sure if its possible or if i should just use pygame

  • @guybar8128
    @guybar8128 3 ปีที่แล้ว +16

    The code does not check the position of the food so it can spawn on top of the snake. Other than that, great video.

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

      also if you press two non opposite arrow keys rapidly the snake will do a 180 degree turn resulting in game over

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

    Do we need to download the file game before starting programming? I mean the file contains some image folders, sound folders,...stuff like that ;-;

  • @prakashgond9388
    @prakashgond9388 8 หลายเดือนก่อน +1

    Thank you so much Sir ...!!!
    Love from Bharat...!!!

  • @CristianoRonaldo-mb1jb
    @CristianoRonaldo-mb1jb 3 ปีที่แล้ว +1

    very nice

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

    I'm asking for help cuz I don't know much of python, but how can I make the code work? it keeps saying that a "float" cannot be used as an "int", and then proceed to show me wich lines aren't working (those being line 159, 33, 336 and 312). I know on paper what this means but I don't know how to correct the error. How?

  • @zik0v
    @zik0v ปีที่แล้ว +3

    Thanks for the tutorial!
    Can someone help on how to disable food from spawning in the snake body?
    As the snake gets longer it gets more common.

  • @davidbandini3484
    @davidbandini3484 ปีที่แล้ว +4

    Thank you so much for the lesson, very easy to follow for a super beginner like me!! I have a question if in the "Background" I want to put a picture of a snake, for example, how can do it?

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

      I can tell you the solution but do you want it now

  • @RobotIsaac12
    @RobotIsaac12 19 วันที่ผ่านมา

    Amazing explanation. Short, crisp and to the point.
    Unknowingly you taught me a lot about classes and objects.
    Thanks!
    Edit : I am trying to add on to your project by making changes such as snake head of different color, storing a high score, pause button and a restart button!

  • @fall2landers
    @fall2landers 27 วันที่ผ่านมา

    I feel like my attention span doesn't exist while I work on whatever while listening to bro code talk about snakes in the background of my mind...

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

    Amazing tutorial 👍

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

    that's a great tutorial and the 1st snake I do for the first time for me

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

    Imagine how much better it would be if javascript was able to be added to it

  • @muffinhead3115
    @muffinhead3115 9 หลายเดือนก่อน +1

    this video is very helpful! but I kinda got stuck on the 'label' part...
    when I typed : label =label(window, text="Score:{}".format(score), font=('consolas', 40))
    it says: name 'label' is not defined. Did you mean: 'Label'?
    what do I need to do to fix it?

    • @sarv4265
      @sarv4265 9 หลายเดือนก่อน +2

      try this: label = Label(window, text="Score:{}".format(score), font=('consolas', 40))

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

    what if I would like to make the food will not land on the body of the snake (every block after the head of the snake)??

  • @juankorsia7909
    @juankorsia7909 2 ปีที่แล้ว

    Amazing! I apreciate your time...

  • @whypeople4719
    @whypeople4719 2 ปีที่แล้ว

    Бро, ты лучший, долго пытался освоить питон и только ты смог мне в этом помочь

  • @yorkshire6573
    @yorkshire6573 ปีที่แล้ว +3

    Hey how did you converted into pixels ? At 9:49

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

    Superb tutorial. Next time, can you show a pixel graph for reference. I was trying to understand the calculations for how the window is centered for a while. I eventually saw that the pixel graph is drastically different from the Cartesian graph (the graphs we use in high school and college).

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

    Excellent tutorial!

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

    Nice tutorial

  • @IGNITED-ofcl
    @IGNITED-ofcl 9 หลายเดือนก่อน +1

    it is showing me a problem :
    Expected indented block Pylance [Ln 95, Col 1]
    in the check collisions but i have followed everything nicely as you explained in the video

  • @dulanjanarukshan5878
    @dulanjanarukshan5878 3 ปีที่แล้ว

    Great job. I

  • @peaceangell
    @peaceangell 2 ปีที่แล้ว

    I love ur videos.Keep it up

  • @TimeWrapChronicales
    @TimeWrapChronicales 3 ปีที่แล้ว +3

    Thank you bro code I like all your videos

  • @juanandresmatallana1682
    @juanandresmatallana1682 3 ปีที่แล้ว +6

    Do you have some recomended books for learning Python???

    • @BroCodez
      @BroCodez  3 ปีที่แล้ว +5

      anything by O'Reilly

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

    @Bro Code Hello. Good day! Can you do a video on how to add menu buttons? Thank you.

  • @user-es2xt4ep7p
    @user-es2xt4ep7p 5 หลายเดือนก่อน

    Your tutorials are amazing. i fell like a pro while just watching your videos. but i would like to know how to transform those codes into an executable file.

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

    Bro you are the best, I tried to master python for a long time and only you could help me with this

  • @user-bo3eu5ip8i
    @user-bo3eu5ip8i ปีที่แล้ว

    what app do you use to run the python?

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

    Followed along. Got so lost. Classes and functions are still kind of new for me, I did end up finishing the project tho.

  • @oximas-oe9vf
    @oximas-oe9vf ปีที่แล้ว +3

    question: which is better for simple projects and games , Tkinter, pygame or something else?
    and what are the pros and cons of each(Tkinter vs Pygame)?
    Note: I havn't learned about pygame yet

    • @PreslavKolev
      @PreslavKolev ปีที่แล้ว +3

      Pygame uses sdl2 which is written in c++. This makes it more performant but you still lose about 60% of the c++ performance. Thinker on the other hand is a gui library and is not made for games

    • @oximas-oe9vf
      @oximas-oe9vf ปีที่แล้ว +2

      @@PreslavKolev thanks for the information

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

    thanks, very good video

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

    Hi, great Video but i have a question...
    How does the game over screen get triggered? i know its working because i followed and tried but what told the gameover screen to appear? Is it just because check_colission returned true and next thing in script is this screen? is this how it works?

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

    Great Video

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

    very good video!!! It took me about 2 hours, but I eventually got it right 😅Greetings from Mexico!

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

      How many days are you learning python language

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

    Great concise video.
    My food wasn't appearing in proper coordinates. Took me ages to check line by line lol

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

      howd u you solve this? i have the same error too I think, of the food being seen as a float (maybe u had the same problem??)

    • @fr3sh636
      @fr3sh636 5 หลายเดือนก่อน

      @@supermoneyd1081 did u solve it? ive got the same problem

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

    Cool

  • @kingofdoom6955
    @kingofdoom6955 2 ปีที่แล้ว

    VERY AWESOME!!!

  • @samirtouati2219
    @samirtouati2219 5 หลายเดือนก่อน

    Great video.

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

    I thought I was literally copying the video as it went but now I get to debug tomorrow as a learning experience

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

    Me not understanding a bit because I don't know python but still watching because it's interesting

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

    Bro is a menace making a game in Tkinter which is used for making apps

  • @dillonpaul1498
    @dillonpaul1498 11 หลายเดือนก่อน

    how did bro code get the color picker window for the snake color?

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

    Can you make a c# tutorial and other games we can make?

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

    when i want to make it so that the snake apears back onto the screen when going against a wall how do i do tht? (say i were going right and the snake would collide it would appear on the left again)

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

      You just have to teleport the head coordinate, just add this function to your code, it checks whether we should teleport the snake or not, and also, don't forget to delete the check collisions with the wall from the current code, otherwise they will conflict:
      *This is the function:
      def check_teleport(snake):
      x, y = snake.coordinates[0]
      if x < 0:
      #Setting the X coordinate to be the other end of the map
      x = GAME_WIDTH - SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake X coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if x >= GAME_WIDTH:
      #Setting the X coordinate to be the other end of the map
      x = -SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake X coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if y < 0:
      #Setting the Y coordinate to be the other end of the map
      y = GAME_HEIGHT - SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake Y coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if y >= GAME_HEIGHT:
      #Setting the Y coordinate to be the other end of the map
      y = -SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake Y coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      *You should also call it inside the "next_turn" function right above the part that checks if we get the food.
      If you are still having trouble, here's the full code for you to test, with this new implementation:
      from ssl import AlertDescription
      from tkinter import *
      import random
      from matplotlib.pyplot import fill
      #Global Variables
      SCORE_FONT_SIZE = 25
      GAME_WIDTH = 400
      GAME_HEIGHT = 400
      SPEED = 50
      SPACE_SIZE = 10
      BODY_PARTS = 3
      SNAKE_COLOR = "#8AC847"
      FOOD_COLOR = "#EDD455"
      BACKGROUND_COLOR = "#000000"
      class Snake:
      def __init__(self):
      self.body_size = BODY_PARTS
      self.coordinates = []
      self.squares = []
      for i in range(0, BODY_PARTS):
      self.coordinates.append([0, 0])
      for x, y in self.coordinates:
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
      self.squares.append(square)
      class Food:
      def __init__(self):
      #Defining where the food should spawn randomly
      x = random.randint(0, (GAME_WIDTH/SPACE_SIZE)-2) * SPACE_SIZE #Converting to pixels by multiplyig by the space size
      y = random.randint(0, (GAME_HEIGHT/SPACE_SIZE)-2) * SPACE_SIZE
      self.coordinates = [x, y]
      canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food") #It needs a starting corner and an ending corner, thats why we provide x and y as the initial values and x + SPACE_SIZE AND y + SPACE_SIZE as the ending corners
      def next_turn(snake, food):

      x , y = snake.coordinates[0]
      if direction == "up":
      y -= SPACE_SIZE
      elif direction == "down":
      y += SPACE_SIZE
      elif direction == "left":
      x -= SPACE_SIZE
      elif direction == "right":
      x += SPACE_SIZE
      #Updating the snake coordinates
      snake.coordinates.insert(0, (x, y))
      square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
      snake.squares.insert(0, square)
      check_teleport(snake)
      #Checking if we caught the food, and if we did, we update the score
      if x == food.coordinates[0] and y == food.coordinates[1]:
      global score
      score += 1
      label.config(text="Score:{}".format(score))
      canvas.delete("food")
      food = Food()
      else:
      #We only delete the last part of the snake if we did not get the food
      #Deleting the squares of the snake that should not appear on screen
      del snake.coordinates[-1]
      canvas.delete(snake.squares[-1])
      del snake.squares[-1]

      #Checking if we hit something we should have not hit
      if check_collisions(snake):
      game_over()
      else:
      #Recalling the same function after the game speed value so we can loop
      window.after(SPEED, next_turn, snake, food)
      def change_direction(new_direction):

      global direction
      if new_direction == 'left':
      if direction != 'right':
      direction = new_direction
      elif new_direction == 'right':
      if direction != 'left':
      direction = new_direction

      elif new_direction == 'up':
      if direction != 'down':
      direction = new_direction
      elif new_direction == 'down':
      if direction != 'up':
      direction = new_direction
      def check_collisions(snake):
      #Unpacking the head of the snake
      x, y = snake.coordinates[0]
      # if x < 0 or x >= GAME_WIDTH:
      # return True
      # elif y < 0 or y >= GAME_HEIGHT:
      # return True
      #Checking if we collide with any part of the snake, excluding the head
      for body_part in snake.coordinates[1:]:
      if x == body_part[0] and y == body_part[1]:
      return True
      #Returning false if no collisions were detected
      return False
      def check_teleport(snake):
      x, y = snake.coordinates[0]
      if x < 0:
      #Setting the X coordinate to be the other end of the map
      x = GAME_WIDTH - SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake X coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if x >= GAME_WIDTH:
      #Setting the X coordinate to be the other end of the map
      x = -SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake X coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if y < 0:
      #Setting the Y coordinate to be the other end of the map
      y = GAME_HEIGHT - SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake Y coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      if y >= GAME_HEIGHT:
      #Setting the Y coordinate to be the other end of the map
      y = -SPACE_SIZE
      new_coord = (x,y)
      #Updating the snake Y coordinates to teleportate it to the other end of the map
      snake.coordinates[0] = new_coord
      def game_over():
      canvas.delete(ALL)
      canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2, font=('consolas', 30), text="GAME OVER", fill="red", tag="game_over")
      #Window Configuration
      window = Tk()
      window.title("Snake")
      window.resizable(False, False)
      #Initial Values
      score = 0
      direction = 'down'
      #Creating the label that updates the score
      label = Label(window, text="Score:{}".format(score), font=('consolas', SCORE_FONT_SIZE))
      label.pack()
      #Creating the canvas where the snake will run
      canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
      canvas.pack()
      #Opening the game in the center of the screen
      window.update()
      window_width = window.winfo_width()
      window_height = window.winfo_height()
      screen_width = window.winfo_screenwidth()
      screen_height = window.winfo_screenheight()
      #Calculating the coordinates for opening the game centralized in the screen
      x = int((screen_width/2) - (window_width/2))
      y = int((screen_height/2) - (window_height/2))
      window.geometry(f"{window_width}x{window_height}+{x}+{y}")
      #Key bindings for controlling the snake
      window.bind('', lambda event: change_direction('left'))
      window.bind('', lambda event: change_direction('right'))
      window.bind('', lambda event: change_direction('up'))
      window.bind('', lambda event: change_direction('down'))
      snake = Snake()
      food = Food()
      next_turn(snake, food)
      window.mainloop()

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

    Why do I get IndexError: list index out of range when it runs snake.coordinates[0] ?

  • @nunocgas9206
    @nunocgas9206 3 ปีที่แล้ว +3

    Great tutorial!

    • @stivenkasa8080
      @stivenkasa8080 2 ปีที่แล้ว

      Please help how to get the white game table on the game tkinter

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

    My snake don't move right every other direction works but if i press right the snake reduces itself to 1 square but after that i can press up/ down and the snake move in the pressed direction

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

    Hello sir, when i run the program it says : " 'snake ' object has no attribute 'coordinates'. "
    Please help

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

    how would you make it so that when the snake goes off screen instead of showing game over he reappears on the exact opposite side of the screen that he had originally gone off from?

  • @trishandas4500
    @trishandas4500 3 ปีที่แล้ว

    excellent video!

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

    Thank you teaching

  • @istproduction1759
    @istproduction1759 2 ปีที่แล้ว

    help at if direction == "up":
    y -= SPACE_SIZE
    it says not defined

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

    I could not do the restart method. Can you help me?

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

    it's so fun and relax

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

    You lessons are very intuitive and ❤’em.. Please can you help me out to create a play again or restart button… I have been trying it for more than three days now but it’s not functioning 😮😮😢.

  • @dbsvlogs-yw4bv
    @dbsvlogs-yw4bv 23 วันที่ผ่านมา

    bro which coding app you using in your pc

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

    Hello. Good day! Can you do a video on how to add menu buttons? Thank you.