Let's code a SNAKE GAME in python! 🐍

  Рет қаралды 698,715

Bro Code

Bro Code

Күн бұрын

Пікірлер: 716
@BroCodez
@BroCodez 4 жыл бұрын
# ************************************** # 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 жыл бұрын
Dude! You are a life saver!
@piyushsinghal9518
@piyushsinghal9518 3 жыл бұрын
sup
@ayssarrrr
@ayssarrrr 3 жыл бұрын
Thanks bro
@aryanpandey1959
@aryanpandey1959 3 жыл бұрын
Sir is code ko copy kar sakte h?
@musicalzone123
@musicalzone123 3 жыл бұрын
how can I pack all code so I can use it with other modules too..
@chasengonzales85
@chasengonzales85 2 жыл бұрын
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.
@Heart_toHearts
@Heart_toHearts 8 ай бұрын
past the full code in chat box fr me
@nalajalabhuvana8788
@nalajalabhuvana8788 8 ай бұрын
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()
@JustAhmed_yt
@JustAhmed_yt 3 ай бұрын
@@Heart_toHearts # ************************************ # 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()
@Hansen_0101
@Hansen_0101 2 ай бұрын
Mind sharing the code?
@yxtom1465
@yxtom1465 2 ай бұрын
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()
@kaikai5356
@kaikai5356 3 жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
hey
@unintentionaltime
@unintentionaltime 2 жыл бұрын
Either I'm finally starting to understand python, or you are just a very good teacher.
@sarangm3152
@sarangm3152 2 жыл бұрын
He is a good teacher
@H3XED_OwO
@H3XED_OwO Жыл бұрын
probably both
@Toolterra
@Toolterra 5 ай бұрын
You are a god
@moukaloka9543
@moukaloka9543 4 жыл бұрын
bro you are the TUTORIAL MASTER !!!
@stivenkasa8080
@stivenkasa8080 3 жыл бұрын
Please help how to get the white game table on the game tkinter
@shaliniminz2743
@shaliniminz2743 2 жыл бұрын
Output is stop only for 1second what to do
@Short.Vs_code
@Short.Vs_code 11 ай бұрын
​@@shaliniminz2743 same with me
@lucasshortss_
@lucasshortss_ 2 жыл бұрын
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
@dan1locksk
@dan1locksk Жыл бұрын
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
@techkenya2
@techkenya2 Жыл бұрын
been looking for this, thanks
@eklavya22k34
@eklavya22k34 Жыл бұрын
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 Жыл бұрын
how is it going so far? are you making any progress?
@dungvuong7201
@dungvuong7201 Жыл бұрын
@@eklavya22k34 I also encountered the same situation. But I coded according to yours and got an error
@farissofea8307
@farissofea8307 Жыл бұрын
Im geting positional arguments follow keyword arguments. Why is that and how to fix it?
@lolski-sr4yy
@lolski-sr4yy 9 ай бұрын
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 8 ай бұрын
THANK YOU SO MUCH DUDE I WAS HAVING THE SAME PROBLEM ITS FIXED NOW
@cindrella4252
@cindrella4252 8 ай бұрын
THANKS A LOTT BROOO!!! I WAS LITERALLY STRUGGLING SINCE YESTERDAY!!
@kailenbains4418
@kailenbains4418 8 ай бұрын
THANK YOU!!
@TheMeeplet
@TheMeeplet 6 ай бұрын
Much appreciated
@vic-bender
@vic-bender 5 ай бұрын
This can also be fixed by putting an "int(GAME_WIDTH / SPACE_SIZE)" instead of "(GAME_WIDTH / SPACE_SIZE)" on lines 37 and 38, as it simply converts the float to an integer, but your solution also works!
@kiendra
@kiendra 5 ай бұрын
my slow ahh would turn this quick 30 minute project into a 5 hour procrastination journey
@emhs_tech
@emhs_tech 5 ай бұрын
3 weeks 💀
@Ayush_DragonMaster-
@Ayush_DragonMaster- Ай бұрын
10 hours 💀
@Pelmen323
@Pelmen323 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
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?
@Gunsi-kb2xq
@Gunsi-kb2xq 2 жыл бұрын
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 2 жыл бұрын
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
@luthersonline
@luthersonline 3 жыл бұрын
Thank you for this amazing series! Getting myself started in learning programming :)
@stivenkasa8080
@stivenkasa8080 3 жыл бұрын
Please help how to get the white game table on the game tkinter
@MrCoolerMan1
@MrCoolerMan1 Жыл бұрын
@@stivenkasa8080 bg='white' or BACKGROUND_COLOR='white'
@fasena71
@fasena71 Жыл бұрын
I think that you have to write False twice because it means window width and height , two values . Very good tutorial
@eklavya22k34
@eklavya22k34 Жыл бұрын
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 8 ай бұрын
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()
@RobotIsaac12
@RobotIsaac12 7 ай бұрын
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!
@maftunaabduhalilova1323
@maftunaabduhalilova1323 Ай бұрын
wow amazing 😍 you explain it very simple and did it very cool 👍👍👍 best tutorials only in this channel, I like it keep going, my motivation for coding increases by this kind of tutorials
@Ayush_DragonMaster-
@Ayush_DragonMaster- Ай бұрын
For people who have Python 3.16 and above you can write label = Label(window, text=f"Score: {score}") instead of writing .format{score}
@Ayush_DragonMaster-
@Ayush_DragonMaster- Ай бұрын
it is also known as an f string
@Videozforyou
@Videozforyou Ай бұрын
Amazing video, keep up the good work Bro
@kralbalkizar
@kralbalkizar 3 жыл бұрын
Well spent 30 minutes of Saturday morning! :) Great job, I would like to code this error-less way too ;)
@mdjackhan
@mdjackhan 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 :) )
@Satoshiisnaruto
@Satoshiisnaruto Жыл бұрын
Thanks for taking the time to put all this on the internet for all of us to look at free. Very awesome
@theonlysodman4042
@theonlysodman4042 11 ай бұрын
Can anyone help me with an issue that I am having with this program? I followed the text exactly as he had typed it yet I am still getting the same error message. It says: "Float" object can not be interpreted as integer. I don't know why I keep getting this error. The program is perfectly in sync with his up until I create the food object. I don't understand. Can anyone help?
@oliviaalicia9756
@oliviaalicia9756 11 ай бұрын
I had this problem that was coming up under the Food class. I had to redefine x and y as int. def __init__(self): x = random.randint(0,int(GAME_WIDTH/SPACE_SIZE)-1) * SPACE_SIZE y = random.randint(0,int(GAME_HEIGHT/SPACE_SIZE)-1) * SPACE_SIZE
@captainvipgames3552
@captainvipgames3552 8 ай бұрын
Put // instead of /
@yihffjjg
@yihffjjg 8 ай бұрын
​@@captainvipgames3552 preciate bro
@keerthana4386
@keerthana4386 6 ай бұрын
Give the complete code in Chatgpt and tell it to correct it😊
@GameAndArt-o4g
@GameAndArt-o4g 5 ай бұрын
@@oliviaalicia9756thank you I had the same problem!🤩🤩🤩
@hamza582
@hamza582 3 жыл бұрын
Thank you, sir, Good project with a good explanation.
@guybar8128
@guybar8128 3 жыл бұрын
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 2 жыл бұрын
also if you press two non opposite arrow keys rapidly the snake will do a 180 degree turn resulting in game over
@claudiofavoreto3126
@claudiofavoreto3126 Жыл бұрын
Great job! One day I'll be programming like you! =] Thanks for sharing this programming lesson. One more subscriber.
@joniole7714
@joniole7714 2 жыл бұрын
nice simple game tutorial Bro.. Thank you so much for this tutorial..
@marcusworrell7175
@marcusworrell7175 2 жыл бұрын
Very cool and instructional. Thanks Bro!!
@Muhammadyusuf33-n6s
@Muhammadyusuf33-n6s 2 жыл бұрын
These codes are really understandble, i did same thing with you while getting what you're saying
@SomeoneWhoScrollsonYT
@SomeoneWhoScrollsonYT 2 ай бұрын
3:55 u probably need to do it twice because you can resize both sides of the window, which means you can most likely make the window resizable only by one side if you only put false once
@Just_Jude100
@Just_Jude100 8 ай бұрын
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).
@SeniorFancy
@SeniorFancy 4 ай бұрын
Thank you! I have wanted to code a game in python forever!
@NORIMAKi09
@NORIMAKi09 2 жыл бұрын
i've made this game by this video! thank you from japan!
@quequeixo
@quequeixo 2 жыл бұрын
Nice game maker tutorial bro, i did it on live stream, it was awesome
@AmarMustafi-y4j
@AmarMustafi-y4j 3 күн бұрын
Never skiping an ad for this guy
@kyablonska95
@kyablonska95 Жыл бұрын
thanks a lot for sharing it! you are helping to make learning python more fun and enjoyable :)
@Ayush_DragonMaster-
@Ayush_DragonMaster- Ай бұрын
Everybody here is the code with no errors and a restart button at the end: from tkinter import * import random GAME_WIDTH = 700 GAME_HEIGHT = 700 SPEED = 100 # Increase this value to slow down the game 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): self.generate_food() def generate_food(self): x = random.randint(0, int(GAME_WIDTH / SPACE_SIZE) - 1) * SPACE_SIZE y = random.randint(0, int(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): if direction is None: window.after(SPEED, next_turn, snake, food) return 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.generate_food() # Generate new 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' and direction != 'right': direction = new_direction elif new_direction == 'right' and direction != 'left': direction = new_direction elif new_direction == 'up' and direction != 'down': direction = new_direction elif new_direction == 'down' and direction != 'up': direction = new_direction # Ensure the game starts when the direction is first set if not game_started[0]: game_started[0] = True next_turn(snake, food) 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.5, font=('consolas', 70), text="GAME OVER", fill="red", tag="gameover") restart_button.place(relx=0.5, rely=0.65, anchor=CENTER) # Show restart button slightly lower def reset_game(): global snake, food, direction, score, game_started # Clear canvas canvas.delete(ALL) # Reset variables snake = Snake() food = Food() direction = None score = 0 game_started[0] = False label.config(text="Score:{}".format(score)) # Start the game again restart_button.place_forget() # Hide restart button next_turn(snake, food) window = Tk() window.title("Snake game") window.resizable() score = 0 direction = None # Set initial direction to None game_started = [False] # Add a flag to check if the game has started 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.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')) restart_button = Button(window, text="Restart", font=('consolas', 20), bg="red", fg="white", command=reset_game) restart_button.place_forget() # Hide restart button initially snake = Snake() food = Food() # Call next_turn but only start moving when a direction is set next_turn(snake, food) window.mainloop() (P.S I don't mean to discredit BroCodez but instead I just wanted to help out people struggling to fix the errors.)
@arjun20822
@arjun20822 3 жыл бұрын
Thanks man i appriciate you efforts 👍👍it amazing tutrorial it helped me a lottt .... I expect more tutorials😊😊
@habibyyub1487
@habibyyub1487 4 ай бұрын
# This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # take input from the user choice = input("Enter choice(1/2/3/4): ") # check if choice is one of the four options if choice in ('1', '2', '3', '4'): try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) except ValueError: print("Invalid input. Please enter a number.") continue if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) # check if user wants another calculation # break the while loop if answer is no next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: print("Invalid Input")
@jdtrrs8186
@jdtrrs8186 Жыл бұрын
very good video!!! It took me about 2 hours, but I eventually got it right 😅Greetings from Mexico!
@riyadsheikh495
@riyadsheikh495 8 ай бұрын
How many days are you learning python language
@khongcobiet
@khongcobiet Жыл бұрын
import turtle import time import random delay = 0.1 # Score score = 0 high_score = 0 # Set up the screen wn = turtle.Screen() wn.title("Snake Game by @TokyoEdTech") wn.bgcolor("green") wn.setup(width=600, height=600) wn.tracer(0) # Turns off the screen updates # Snake head head = turtle.Turtle() head.speed(0) head.shape("square") head.color("black") head.penup() head.goto(0,0) head.direction = "stop" # Snake food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0,100) segments = [] # Pen pen = turtle.Turtle() pen.speed(0) pen.shape("square") pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal")) # Functions def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) # Keyboard bindings wn.listen() wn.onkeypress(go_up, "w") wn.onkeypress(go_down, "s") wn.onkeypress(go_left, "a") wn.onkeypress(go_right, "d") # Main game loop while True: wn.update() # Check for a collision with the border if head.xcor()>290 or head.xcor()290 or head.ycor() high_score: high_score = score pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) # Move the end segments first in reverse order for index in range(len(segments)-1, 0, -1): x = segments[index-1].xcor() y = segments[index-1].ycor() segments[index].goto(x, y) # Move segment 0 to where the head is if len(segments) > 0: x = head.xcor() y = head.ycor() segments[0].goto(x,y) move() # Check for head collision with the body segments for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" # Hide the segments for segment in segments: segment.goto(1000, 1000) # Clear the segments list segments.clear() # Reset the score score = 0 # Reset the delay delay = 0.1 # Update the score display pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) time.sleep(delay) wn.mainloop() work in python 3
@juanandresmatallana1682
@juanandresmatallana1682 3 жыл бұрын
Do you have some recomended books for learning Python???
@BroCodez
@BroCodez 3 жыл бұрын
anything by O'Reilly
@KarmjeetsinhChauhan
@KarmjeetsinhChauhan 2 ай бұрын
Thank you for this amazing game information !!
@rodydinha3396
@rodydinha3396 2 жыл бұрын
you are amaaaaaaazing !!! i hope you make a series about kivy library and the other important libraries
@TricksChronicals
@TricksChronicals 3 жыл бұрын
Thank you bro code I like all your videos
@TricksChronicals
@TricksChronicals 3 жыл бұрын
WOW
@chinojosee2610
@chinojosee2610 Жыл бұрын
Bro u are tutorial master!!! U gave me ideas to make my final project for my python class !!!!!
@JDgiggles
@JDgiggles Жыл бұрын
Thank you for this. I'm really excited to learn and develop my coding skills
@shiv6574
@shiv6574 2 жыл бұрын
i am so happy i have searches the whole for a tutorial to make a game using python
@oximas-oe9vf
@oximas-oe9vf 2 жыл бұрын
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 2 жыл бұрын
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
@Cr3cked
@Cr3cked 5 ай бұрын
3:55 Actually You Write False Twice To Make Sure The User Cant Resize Both The Windows Height AND Width.
@flyh1ghgd182
@flyh1ghgd182 2 жыл бұрын
you gotta give this man some respect, he coded snake game with python. Python is a snake. He is literally coding a snake game with snake
@KLOVEpeacePro
@KLOVEpeacePro 2 жыл бұрын
hmm not surprise human give birth to human , snake give birth to snake so law of nature
@prakharposwal9
@prakharposwal9 4 жыл бұрын
you are a really good teacher
@oMqngo
@oMqngo 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 жыл бұрын
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()
@gamelifer234
@gamelifer234 2 жыл бұрын
Great concise video. My food wasn't appearing in proper coordinates. Took me ages to check line by line lol
@supermoneyd1081
@supermoneyd1081 Жыл бұрын
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 Жыл бұрын
@@supermoneyd1081 did u solve it? ive got the same problem
@blurryface560
@blurryface560 6 ай бұрын
i am also stuck bro help needed
@prakashgond9388
@prakashgond9388 Жыл бұрын
Thank you so much Sir ...!!! Love from Bharat...!!!
@megabitsss
@megabitsss Жыл бұрын
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?
@Ayush_DragonMaster-
@Ayush_DragonMaster- Ай бұрын
Not necessary unless you are centering it
@fall2landers
@fall2landers 7 ай бұрын
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...
@prernasharma2048
@prernasharma2048 2 жыл бұрын
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!!😁
@Amir_Plays_non_stop
@Amir_Plays_non_stop 3 жыл бұрын
Wahooooo Finished! Great tutorial.
@BroCodez
@BroCodez 3 жыл бұрын
Thanks for watching all the videos GaMe tOut!
@Amir_Plays_non_stop
@Amir_Plays_non_stop 3 жыл бұрын
@@BroCodez No thank you for the awesome work!❤ Also do you have a discord that u speak with your viewers?
@stivenkasa8080
@stivenkasa8080 3 жыл бұрын
Please help how to get the white game table on the game tkinter
@Amir_Plays_non_stop
@Amir_Plays_non_stop 3 жыл бұрын
@@stivenkasa8080 can you be more specific?
@stivenkasa8080
@stivenkasa8080 3 жыл бұрын
@@Amir_Plays_non_stop how to open the tutle gepahics
@abhaykaneriya9188
@abhaykaneriya9188 Ай бұрын
thanks bro for this amazing project
@markgil7777
@markgil7777 Ай бұрын
Youre so cooooooooool bro, i hope one day i can code without watching tutorial
@peaceangell
@peaceangell 3 жыл бұрын
I love ur videos.Keep it up
@manhnguyenminh9730
@manhnguyenminh9730 3 жыл бұрын
Thank you so much
@davidbandini3484
@davidbandini3484 2 жыл бұрын
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 Жыл бұрын
I can tell you the solution but do you want it now
@emhs_tech
@emhs_tech 5 ай бұрын
@@bepositive271 can u say it now ? 💀
@amirchegg
@amirchegg 3 жыл бұрын
hey bro👋 is python series completed or there will be more upcoming videos?
@ClockWiseIsAGreatDeveloper
@ClockWiseIsAGreatDeveloper 3 жыл бұрын
I think its completed
@redcurated4302
@redcurated4302 Жыл бұрын
Followed along. Got so lost. Classes and functions are still kind of new for me, I did end up finishing the project tho.
@whypeople4719
@whypeople4719 2 жыл бұрын
Bro you are the best, I tried to master python for a long time and only you could help me with this
@zik0v
@zik0v 2 жыл бұрын
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.
@BeatsByEndless
@BeatsByEndless Жыл бұрын
when trying to run it I get an error saying " window = Tk() ^^ NameError: name 'Tk' is not defined" Can anyone help me out?
@Showbtb
@Showbtb Жыл бұрын
me too
@Levi35821
@Levi35821 Ай бұрын
Have you downloaded tkinter?
@nuonduch585
@nuonduch585 3 жыл бұрын
Hey bro 19/11/21 I finish your python tutorial beginning .Thanks Thanks you so much
@nunocgas9206
@nunocgas9206 3 жыл бұрын
Great tutorial!
@stivenkasa8080
@stivenkasa8080 3 жыл бұрын
Please help how to get the white game table on the game tkinter
@sampython4825
@sampython4825 2 жыл бұрын
I found a big bug in the game. if you are facing left and you press Up and immediately after press right. before the snake has had time to move up than the snake will die
@automaticbox
@automaticbox 2 жыл бұрын
I believe you can fix that with adding "if direction != 'left, up right': direction != new_direction" to the change_direction. not sure though just thinking.
@vic-bender
@vic-bender 5 ай бұрын
you could put in a time.sleep(0.05) somewhere in the change_direction that will make you unable to change direction for long enough that the snake will move in the direction you want before you can change it again
@tajriaakter8029
@tajriaakter8029 2 күн бұрын
Bro you'r the goat😭
@kokojamba232
@kokojamba232 Жыл бұрын
for collosion detection you could just turn the squares list into a set and check if its smaller than the original list
@solomonezra1253
@solomonezra1253 Жыл бұрын
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 😮😮😢.
@mrbulk-f4m
@mrbulk-f4m 2 жыл бұрын
Nice!👍 A quick and easy snek game.
@informatique-ham
@informatique-ham 7 ай бұрын
nice and good explanAtion. Thanks
@DotorSquido-j7r
@DotorSquido-j7r 2 ай бұрын
hey bro code I'm getting a error under the food class I'm getting " 'int' object has no attribute '_create' " could you possibly tell me how to fix this?
@ippo902
@ippo902 Ай бұрын
me too, maybe beacuse after 3 years tkinter changed and now it need another way of writing...
@muffinhead3115
@muffinhead3115 Жыл бұрын
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 Жыл бұрын
try this: label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
@TheAimTrainer
@TheAimTrainer 3 ай бұрын
The only issue I’m having with this is every time I run the code, only 1 square shows up and then it deletes itself causing a game over. Everything is added according to the video, but the issue started when the snake was supposed to go all the way down like a line. Imma check back on the code a little later and update this comment if anything changes
@juzosuzuya9297
@juzosuzuya9297 8 ай бұрын
that's a great tutorial and the 1st snake I do for the first time for me
@Alpha_jr_jb
@Alpha_jr_jb 3 ай бұрын
How can I install module tkinter
@hbbx009
@hbbx009 2 ай бұрын
it should be built in though?
@graon4880
@graon4880 9 ай бұрын
can anyone help me with this question, why can you call the function name within the function at 18:02?
@vasinh838
@vasinh838 7 ай бұрын
you still need help ?
@Callie_With_a_Bible
@Callie_With_a_Bible 3 ай бұрын
​@@vasinh838Leave it here anyway in case someone else has the same question
@sxyl.
@sxyl. Ай бұрын
Hello! May I ask what is the version of your pycharm? Because Im using the latest version which is 2024.3.1.1 (huhu) it looks like mine is different than yours and its not working- (Like, the game is not showing up when you click the "run" or "debug") Am I tripping? 😓
@toonytoy
@toonytoy Жыл бұрын
Amazing tutorial 👍
@Barakaisack-n6b
@Barakaisack-n6b Ай бұрын
what was the aim of putting 'newdirection' in def direction('newdirectio')?sorry I'm a begginer
@NetSkillNavigator
@NetSkillNavigator 3 жыл бұрын
Superb tuts!
@nalajalabhuvana8788
@nalajalabhuvana8788 8 ай бұрын
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()
@BEAST_MODE-j6e
@BEAST_MODE-j6e Жыл бұрын
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.
@James-ci5ql
@James-ci5ql 17 күн бұрын
Question: When I run and check the code to see if a random red dot appears (at about 11:20 into the video), I get an error message in Pycharm. It says that, in the Food class, the fraction "GAME_WIDTH / SPACE_SIZE)" (as well as "(GAME_HEIGHT / SPACE_SIZE)"), both naturally return floats due the division operator (/). Once I either, chang the operator from "/" to "//" or rewrite the code as "int(GAME_HEIGHT / SPACE_SIZE)", it works. Can anyone explain why the code works for him when he runs it at that point, and not me, unless I make the above corrections?
@yorkshire6573
@yorkshire6573 2 жыл бұрын
Hey how did you converted into pixels ? At 9:49
@EduTechNeer
@EduTechNeer Жыл бұрын
Not sure why but at time stamp 11:24 I had to use integer division to get it to work.
@abc-nt3vl
@abc-nt3vl 4 ай бұрын
Exactly what you changed in the code?
@EduTechNeer
@EduTechNeer 4 ай бұрын
@@abc-nt3vl It's been a while since I have done it but what i remember is when I used division at the 11:24 Mark. I had to use "//". the division sign twice so as not to return a float value but an integer value. Studying for my drone recertification test right now. I will try and go back later today or tomorrow to see exactly what I did.
@abc-nt3vl
@abc-nt3vl 4 ай бұрын
Aw I didn't expect this fast reply. Thank you so much! As I am currently doing this code and I was facing error exactly at the time stamp of 11:24 but now it is working. I had left spaces between f string {window_width}x{window_height}+{x}+{y} now that I removed the spaces between them, the code is working fine now. Thank you so much again for your kind reply ❤️❤
@planeetjulian741
@planeetjulian741 3 жыл бұрын
You got a new sub!
@skylineshorts5075
@skylineshorts5075 Жыл бұрын
is this the end of the struggle?
@googlegoogle1610
@googlegoogle1610 3 жыл бұрын
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)??
@JohanneM21
@JohanneM21 Жыл бұрын
Very Nice! 😄
@grumpycat2373
@grumpycat2373 Жыл бұрын
This was really helpful, Thank you!
@HoisinDuckWrap
@HoisinDuckWrap Жыл бұрын
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
@MuhanHe
@MuhanHe Жыл бұрын
what app do you use to run the python?
@ZShark216
@ZShark216 2 жыл бұрын
hey, I have a problem, I just made the part with the food adding score but when I touch the food it does nothing, does anyone else have the same thing?
@user13rs258
@user13rs258 2 жыл бұрын
Just go into your food class and do x = random.randint(0, (GAME_WIDTH/SPACE_SIZE)-1) * SPACE_SIZE And not x = random.randint(0, (GAME_WIDTH/SPACE_SIZE)-1 * SPACE_SIZE) LOOK CAREFULLY BOTH ARE NOT SAME. I DID THIS MISTAKE HOPE IT WILL HELP YOU. and same goes for y
@fireball4thewin108
@fireball4thewin108 2 жыл бұрын
@@user13rs258 when i touch the food the game stops, the snake increases to 4 squares, the score goes up to 2 but the snake stops moving. in the terminal i have a typeerror: 'food' object is not callable the error occurs in line 66 which is food = food() i do not understand why this error occurs
@user13rs258
@user13rs258 2 жыл бұрын
@@fireball4thewin108 I guess something wrong in your food class then... 😅😅 Like the pass statement we put after an 'IF', if we don't know what we have to do in that condition... And so the game stops there and does nothing if called that function... Or here constructor.. check the constructor if there is something wrong.. and food = Food() 🤣🤣 might be you didn't wrote it in capital check...😅😅 And also wait I'm looking into my codes.. 🙂 for you.. I will reply soon
@TheLemontea1
@TheLemontea1 3 ай бұрын
Good stuff
@Pcguy777
@Pcguy777 2 ай бұрын
i have the code down exactly but the window just opens to a grey window with nothing in it and no snake?? ive been trying to troubleshoot it for a really long time. this happens anytime i use the tkinter package
Running "Hello World!" in 10 FORBIDDEN Programming Languages
18:07
I made Games with Python for 10 Years...
28:52
DaFluffyPotato
Рет қаралды 394 М.
小丑女COCO的审判。#天使 #小丑 #超人不会飞
00:53
超人不会飞
Рет қаралды 16 МЛН
Гениальное изобретение из обычного стаканчика!
00:31
Лютая физика | Олимпиадная физика
Рет қаралды 4,8 МЛН
人是不能做到吗?#火影忍者 #家人  #佐助
00:20
火影忍者一家
Рет қаралды 20 МЛН
Let's code a beginner Python BANKING PROGRAM 💰
15:01
Bro Code
Рет қаралды 348 М.
2 YEARS of PYTHON Game Development in 5 Minutes!
4:54
Coding With Russ
Рет қаралды 1 МЛН
AI Learns to Walk (deep reinforcement learning)
8:40
AI Warehouse
Рет қаралды 10 МЛН
20 Programming Projects That Will Make You A God At Coding
14:27
The Coding Sloth
Рет қаралды 1,7 МЛН
Inside the V3 Nazi Super Gun
19:52
Blue Paw Print
Рет қаралды 2,9 МЛН
Making a Game With C++ and SDL2
8:14
PolyMars
Рет қаралды 1,7 МЛН
Please Master This MAGIC Python Feature... 🪄
25:10
Tech With Tim
Рет қаралды 167 М.
Python 101: Learn the 5 Must-Know Concepts
20:00
Tech With Tim
Рет қаралды 1,3 МЛН
小丑女COCO的审判。#天使 #小丑 #超人不会飞
00:53
超人不会飞
Рет қаралды 16 МЛН