Python snake game 🐍

preview_player
Показать описание
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 👟 :
===========================================================
===========================================================

music credits 🎼 :
===========================================================
Creative Commons — Attribution-ShareAlike 3.0 Unported— CC BY-SA 3.0
===========================================================
Twelve Speed by - Slynk
===========================================================
Рекомендации по теме
Комментарии
Автор

#
# 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 =


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



canvas.delete("food")

food = Food()

else:

del snake.coordinates[-1]



del snake.squares[-1]

if check_collisions(snake):
game_over()

else:
window.after(SPEED, next_turn, snake, food)


def

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.bind('<Left>', lambda event: change_direction('left'))
window.bind('<Right>', lambda event: change_direction('right'))
window.bind('<Up>', lambda event: change_direction('up'))
window.bind('<Down>', lambda event: change_direction('down'))

snake = Snake()
food = Food()

next_turn(snake, food)

window.mainloop()

BroCodez
Автор

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

lucasshortss_
Автор

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

kaikai
Автор

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.

chasengonzales
Автор

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

lolski-sryy
Автор

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'

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

danlocksk
Автор

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

luthersonline
Автор

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

Balkac
Автор

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

unintentionaltime
Автор

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

fasena
Автор

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

hamza
Автор

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.

eklavyak
Автор

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

Gunsi-kbxq
Автор

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

Satoshiisnaruto
Автор

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 :) )

mdjackhan
Автор

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

claudiofavoreto
Автор

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:

        global score
        global speed
        score += 1



        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.set('down')

window.bind("<w>",  lambda x:new_direction.set('up')) 
window.bind("<a>",  lambda x:new_direction.set('left'))
window.bind("<s>",  lambda x:new_direction.set('down'))  
window.bind("<d>",  lambda x:new_direction.set('right'))
window.bind("<Up>",  lambda x:new_direction.set('up')) 
window.bind("<Left>",  lambda x:new_direction.set('left'))   
window.bind("<Down>",  lambda x:new_direction.set('down'))
window.bind("<Right>",  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







This check is performed before everything, and this allows to change the snake direction only once per main function tick

vadzimfiadotsyeu
Автор

Very cool and instructional. Thanks Bro!!

marcusworrell
Автор

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

JDgiggles
Автор

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

joniole