-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.py
85 lines (69 loc) · 2.18 KB
/
snake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import time
from turtle import Turtle
import json
import sys
import os
def resource_path(relative_path):
""" Get absolute path to resource, works for both dev and PyInstaller bundles. """
if hasattr(sys, '_MEIPASS'):
# If running from a PyInstaller bundle
base_path = sys._MEIPASS
else:
# If running in normal Python environment
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
config_file_path = resource_path('config.json')
# Load configuration
with open(config_file_path, 'r') as config_file:
config = json.load(config_file)
STARTING_POSITIONS=[(0,0),(-20,0),(-40,0)]
SPEED = config["SNAKE_SPEED"]
COLOR = config["SNAKE_COLOR"]
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 add_segment(self, position):
segment = Turtle("square")
segment.color(COLOR)
segment.penup()
segment.goto(position)
self.segments.append(segment)
def extend(self):
self.add_segment(self.segments[-1].position())
def reset(self):
for seg in self.segments:
seg.goto(2000,2000)
self.segments.clear()
self.create_snake()
self.head = self.segments[0]
def move(self):
for seg in range(len(self.segments) - 1, 0, -1):
x_axis = self.segments[seg - 1].xcor()
y_axis = self.segments[seg - 1].ycor()
self.segments[seg].goto(x_axis, y_axis)
self.head.forward(SPEED)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
time.sleep(0.01)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
time.sleep(0.01)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
time.sleep(0.01)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
time.sleep(0.01)