Create main.py file and paste the following code
import turtle as t
import time
import snake
from food import Food
screen = t.Screen()
screen.setup(height=600, width=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
screen.listen()
cobra = snake.Snake()
food = Food()
screen.onkey(cobra.up, "Up")
screen.onkey(cobra.down, "Down")
screen.onkey(cobra.left, "Left")
screen.onkey(cobra.right, "Right")
while True:
screen.update()
time.sleep(0.1)
cobra.snake_move()
if food.distance(cobra.segment[0]) < 15:
food.refresh()
screen.exitonclick()
Create Food.py file and paste the following code
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.color("Yellow")
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.speed("fastest")
def refresh(self):
rand_x = random.randint(-290, 290)
rand_y = random.randint(-290, 290)
self.goto(rand_x, rand_y)
create snake.py file and paste the following code
import turtle as t
STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DIST = 10
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segment = []
self.snake()
def snake(self):
for starting_from in STARTING_POSITION:
tim = t.Turtle("square")
tim.penup()
tim.goto(starting_from)
tim.color("white")
self.segment.append(tim)
def snake_move(self):
for piece_snake in range(len(self.segment) -1, 0 , -1):
x_cor = self.segment[piece_snake - 1].xcor()
y_cor = self.segment[piece_snake - 1].ycor()
self.segment[piece_snake].goto(x = x_cor, y = y_cor)
self.segment[0].forward(MOVE_DIST)
def up(self):
if self.segment[0].heading() != DOWN:
self.segment[0].setheading(90)
def down(self):
if self.segment[0].heading() != UP:
self.segment[0].setheading(270)
def right(self):
if self.segment[0].heading() != LEFT:
self.segment[0].setheading(0)
def left(self):
if self.segment[0].heading() != RIGHT:
self.segment[0].setheading(180)
There you go.... Enjoy
Comments
Post a Comment