Today This Free Friday I am working on project on YouTube a Snake game part 2.
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)
- This part of the code is for the snake body part size.
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
- This part of the code is for the direction for the snake.
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))
snake.coordinates.insert(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
snake.squares.insert(0, square)
del snake.coordinates[-1]
if x == food.coordinates[0] and y == food.coordinates[1]:
global score
score += 1
Label.cofing(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()
- This part of the code is for the coordinates of
- Snake direction
- Food
- SPACE_SIZE
- This part of the code is for the score and to check for collisions.