How to Implement Snake Game in Python

We partner with bada$$ companies that offer products that help our readers achieve their goals! If you purchase through our partner links, we get paid for the referral at no additional cost to you! Please read our disclosure for more info.

Sharing is caring!

Wondering how to implement Snake Game in Python?

Well you just landed on the right blog post.

 

How to implement Snake Game In Python

To properly implement the snake game in python, open a new project, and give it a name of your choice. In that project, we shall have 5 independent files that will coordinate together to implement the snake game. Open five new files and label them as

  1. py – this file contains the main gameplay of the snake game. This is the file that the player essentially runs in their Pycahrm Code Editor for the game to start.
  2. py – the game we develop here can either be a mono – player or dual – player. The essence of the menu is to help the player determine which game mode they intend to play.
  3. py – this file will contain ode that is responsible for the creation and response behavior of

the snake during game play.

  1. py – responsible for keeping track of scores and high scores
  2. py – this file contains code that describes the appearance, position, and behavior of the snake food as it interacts with the snake segments.

Find the detailed code to build a snake game in python below;

FILE 1 : SNAKE.PY

from turtle import Turtle

 

 

STARTING_POSITIONS = [(20, 0), (0, 0), (-20, 0)]

SNAKE_SPEED = 20

UP = 90

DOWN = 270

LEFT = 180

RIGHT = 0

 

 

class Snake:

def init(self,adder): self.adder = adder self.segments = [] self.create_snake() self.head = self.segments[0]

 

def snake_reset(self):

for segments in self.segments:

 

segments.goto(1000, 1000) self.segments.clear() self.create_snake()   self.head = self.segments[0]

def create_snake(self):

for (a,b) in STARTING_POSITIONS:

self.add_segment((a+self.adder, b+self.adder))

 

 

def add_segment(self, position): segment = Turtle(“square”) segment.color(“white”) segment.penup() segment.goto(position) self.segments.append(segment) self.self_damage()

def extend(self): self.add_segment(self.segments[-1].position())

 

def self_damage(self):

for segment1 in self.segments[1:]:

if self.segments[0].distance(segment1) == 5:

print(“You lost\n”)

 

 

def move_snake(self):

for seg_num in range(len(self.segments) – 1, 0, -1): self.segments[seg_num].goto(self.segments[seg_num – 1].xcor(), self.segments[seg_num –

1].ycor())

self.segments[0].forward(SNAKE_SPEED)

 

snake game python

coding

FILE 2: SCOREBOARD.PY

from turtle import Turtle class Scoreboard(Turtle):

def init (self,filename, x,y): super(Scoreboard, self). init () self.x = x

self.y = y

self.filename = filename self.penup() self.color(“White”) self.hideturtle() self.goto(self.x,self.y) self.score = 0

with open(filename) as file:

content = int(file.read()) self.high_score  = content

self.display_score() def display_score(self):

self.clear()

self.write(move=False, arg=f” Score = {self.score} Highscore = {self.high_score}”, font=(“Verdana”, 15, “normal”), align=”center”)

 

 

def reset_game(self):

if self.score >= self.high_score:

with open(self.filename, mode=’w’) as file: file.write(f”{self.score}”)

self.high_score = self.score

 

 

self.score = 0

 

self.display_score()

 

 

def score_up(self): self.score += 1 self.display_score()

 

code for snake game

 

FILE – MENU.PY

from turtle import Screen from main import func1 from main2 import func2 screen = Screen()

 

menu = screen.textinput(title=”Main menu”, prompt=”Options and keys\n Single player – 1\n two player

– 2\n exit – 3″) while True:

if menu == ‘1’: func2() break

elif menu == ‘2’:

 

func1() break

elif menu==’3′: break

else:

print(“Invalid command”) screen.exitonclick()

 

code

 

FILE – MAIN.PY

from random import randint from time import sleep from turtle import Screen

 

from food import Food

from scoreboard import Scoreboard from snake import Snake

 

def func1():

game_is_on = True

score = Scoreboard(filename=”high_score.txt”,x=0,y=280) score2 = Scoreboard(filename=”high_score2.txt”,x=0,y=260) snake = Snake(0)

snake2 = Snake(20)

 

screen = Screen() screen.setup(width=600, height=600) screen.bgcolor(“black”) screen.title(“snake game”) screen.tracer(0)

food = Food() food2 = Food() screen.listen()

screen.onkey(fun=snake.up, key=”Up”) screen.onkey(fun=snake.down, key=”Down”) screen.onkey(fun=snake.left, key=”Left”) screen.onkey(fun=snake.right, key=”Right”) screen.onkey(fun=snake2.up, key=”w”) screen.onkey(fun=snake2.down, key=”s”) screen.onkey(fun=snake2.left, key=”a”) screen.onkey(fun=snake2.right, key=”d”)

 

while game_is_on: screen.update() sleep(0.1) snake.move_snake() snake2.move_snake()

for segment in snake.segments[2:]:

if snake.head.distance(segment) < 10 or snake2.head.distance(segment) < 10 or snake2.head.distance(snake.segments[1]) < 10:

score.reset_game() snake.snake_reset()

for segment in snake2.segments[2:]:

 

if snake2.head.distance(segment) < 10 or snake.head.distance(segment) < 10 or snake.head.distance(snake2.segments[1]) < 10:

score2.reset_game() snake2.snake_reset()

if snake.head.distance(snake2.head) < 10:

score.reset_game() snake.snake_reset() score2.reset_game() snake2.snake_reset()

if snake.head.distance(food) < 20:

food.goto(randint(-280, 280), randint(-280, 280)) score.score_up()

snake.extend()

if snake.head.distance(food2) < 20:

food2.goto(randint(-280, 280), randint(-280, 280)) score.score_up()

snake.extend()

if snake2.head.distance(food) < 20:

food.goto(randint(-280, 280), randint(-280, 280)) score2.score_up()

snake2.extend()

if snake2.head.distance(food2) < 20:

food2.goto(randint(-280, 280), randint(-280, 280)) score2.score_up()

snake2.extend()

if snake.head.xcor() > 290 or snake.head.xcor() < -290 or snake.head.ycor() > 290 or snake.head.ycor() < -290:

score.reset_game() snake.snake_reset()

 

if snake2.head.xcor() > 290 or snake2.head.xcor() < -290 or snake2.head.ycor() > 290 or snake2.head.ycor() < -290:

score2.reset_game() snake2.snake_reset()

 

screen.exitonclick()

 

snake game code

 

code 2

 

FILE 6 – FOOD.PY

from turtle import Turtle from random import randint

 

class Food(Turtle):

def init (self): super(). init () self.shape(“circle”) self.color(“blue”) self.penup()

self.shapesize(stretch_len=0.5, stretch_wid=0.5) self.speed(“fastest”)

self.goto(randint(-280, 280), randint(-280, 280))

 

final code

Sharing is caring!

I love everything about saving, investing, earning, and building net worth.

Leave a Comment