Код: Выделить всё
my_screen = Screen()
my_screen.setup(width=1000, height=600)
my_screen.bgcolor("black")
my_screen.title("My Snake Game")
my_screen.tracer(0)
my_snake = Snake()
food = Food()
scoreboard = Scoreboard()
my_screen.listen()
my_screen.onkey(my_snake.up, "Up")
my_screen.onkey(my_snake.down, "Down")
my_screen.onkey(my_snake.left, "Left")
my_screen.onkey(my_snake.right, "Right")
game_over = False
while not game_over:
my_screen.update()
time.sleep(0.1)
my_snake.move()
# Detect collision with the food
if my_snake.head.distance(food) < 15:
food.refresh_food()
my_snake.grow()
# Detect collision with wall
if my_snake.head.xcor() < -480 or my_snake.head.xcor() > 480 or my_snake.head.ycor() < -280 or my_snake.head.ycor() > 280:
game_over = True
# Detect collision with tail
for segment in my_snake.segments[2:]:
if my_snake.head.distance(segment) < 10:
game_over = True
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
def create_snake(self):
for position in POSITIONS:
self.add_segment(position)
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 move(self):
for seg_num in range(len(self.segments) - 1, 0, -1):
self.head.forward(MOVE_DISTANCE) # Moving distance of head
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)
def grow(self):
self.add_segment(self.segments[-1].position())
def up(self):
if self.head.heading() != 270:
self.head.setheading(90)
def down(self):
if self.head.heading() != 90:
self.head.setheading(270)
def left(self):
if self.head.heading() != 0:
self.head.setheading(180)
def right(self):
if self.head.heading() != 180:
self.head.setheading(0)
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("red")
self.speed("fastest")
self.refresh_food()
def refresh_food(self):
rand_x_cor = random.randint(-480, 480)
rand_y_cor = random.randint(-260, 260)
self.goto(rand_x_cor, rand_y_cor)
Код: Выделить всё
self.head.forward(MOVE_DISTANCE) # Moving distance of headПодробнее здесь: https://stackoverflow.com/questions/790 ... ows-python