Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: AdityaShaw1/hacktoberfest2022
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: thesawankumar/hacktoberfest2022
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Able to merge. These branches can be automatically merged.
  • 2 commits
  • 2 files changed
  • 1 contributor

Commits on Oct 18, 2022

  1. Copy the full SHA
    56440aa View commit details
  2. Create snake.py

    thesawankumar authored Oct 18, 2022
    Copy the full SHA
    eceebc5 View commit details
Showing with 62 additions and 0 deletions.
  1. +61 −0 code/Python/snake_game/snake.py
  2. +1 −0 contributors.toml
61 changes: 61 additions & 0 deletions code/Python/snake_game/snake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from turtle import Turtle, Screen


STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:

def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]

def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)

def move(self):
for seg_num in range(len(self.segments) - 1, 0, -1):
new_x = self.segments[seg_num - 1].xcor()
new_y = self.segments[seg_num - 1].ycor()
self.segments[seg_num].goto(new_x, new_y)
self.segments[0].forward(MOVE_DISTANCE)

def add_segment(self, position):
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)

def reset(self):
for seg in self.segments:
seg.goto(1000, 1000)
self.segments.clear()
self.create_snake()
self.head = self.segments[0]

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

def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)

def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)

def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)

def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
1 change: 1 addition & 0 deletions contributors.toml
Original file line number Diff line number Diff line change
@@ -12,4 +12,5 @@ contributors = [
{ name = "Nitish Pal", bio = "Developer, Mathematician", location = "India" },
{ name = "YorLecaros", bio = "Backend Developer", location = "Peru" },
{ name = "Meghwant", bio = "Web Developer", location = "India" },
{ name = "Sawan Kumar", bio = "Web Developer", location = "India" },
]