Ниже я объединил вашу игру с этим коротким примером , как перемещать сегментированную змею по экрану , который я написал ранее - я удивлен, что ваш поиск SO не включил это .
Я также сделал некоторые другие изменения, чтобы приспособить это движение. Ваша змея превращается из черепахи в список черепах, а последней черепахой в списке является голова змеи. Обработчики стрелок на клавиатуре больше не изменяют направление змеи напрямую, они просто устанавливают новую переменную направления для следующего движения черепахи - это предотвращает конфликты при регулировке черепахи.
Вашему while True:
нет места в управляемом событиями мире, таком как черепаха, поэтому его заменили на событие ontimer()
, иначе вы потенциально можете заблокировать события:
from random import randint
from turtle import Turtle, Screen # force object-oriented turtle
SCORE_FONT = ("Calibri", 40, "bold")
MESSAGE_FONT = ("Calibri", 24, "bold")
SEGMENT_SIZE = 20
def outsidewindow():
(x, y) = snake[-1].pos() # Ask the snake head for its current position
return not (leftwall < x < rightwall and bottomwall < y < topwall)
def gameover():
for segment in snake:
segment.hideturtle()
fruit.hideturtle()
writeturtle.write("Your snake crawled into the garden! Game over!", align="center", font=MESSAGE_FONT)
def showscore(currentscore):
scoreturtledude.undo() # Clear the previous score
scoreturtledude.write(currentscore, align="right", font=SCORE_FONT)
def placefruit():
fruit.hideturtle()
fruit.setposition(randint(-200, 200), randint(-200, 200))
fruit.showturtle()
def startgame():
screen.onkey(None, "space") # So this doesn't run a second time
writeturtle.clear() # Clear the text from the screen
showscore(score)
for segment in snake: # Show the snake
segment.showturtle()
placefruit()
rungame()
def rungame():
global score, snakelength
segment = snake[-1].clone() if len(snake) < snakelength else snake.pop(0)
screen.tracer(False) # segment.hideturtle()
segment.setposition(snake[-1].position())
segment.setheading(snake[-1].heading())
segment.setheading(direction)
segment.forward(SEGMENT_SIZE)
if outsidewindow():
gameover()
return
screen.tracer(True) # segment.showturtle()
snake.append(segment)
if snake[-1].distance(fruit) < SEGMENT_SIZE: # Make the snake eat the fruit when it is nearby
placefruit() # Place another fruit on the screen
snakelength += 1
score += 100
showscore(score)
screen.ontimer(rungame, max(50, 150 - 10 * len(snake))) # Speed up slightly as snake grows
def up():
global direction
current = snake[-1].heading()
if current == 0 or current == 180: # Check if the snake is heading left or right
direction = 90 # Head the snake up
def down():
global direction
current = snake[-1].heading()
if current == 0 or current == 180: # Check if the snake is heading left or right
direction = 270 # Head the snake down
def left():
global direction
current = snake[-1].heading()
if current == 90 or current == 270: # Check if the snake is heading up or down
direction = 180 # Head the snake left
def right():
global direction
current = snake[-1].heading()
if current == 90 or current == 270: # Check if the snake is heading up or down
direction = 0 # Head the snake right
screen = Screen()
screen.bgcolor("orange")
leftwall = -screen.window_width() / 2 # Calculate the left wall
rightwall = screen.window_width() / 2 # Calculate the right wall
topwall = screen.window_height() / 2 # Calculate the top wall
bottomwall = -screen.window_height() / 2 # Calculate the bottom wall
# Creating a turtle to become the snake
head = Turtle("square", visible=False) # Create a new turtle for the snake
head.color("green") # Make the snake green
head.penup() # Disable the turtle's pen, allowing the turtle to move around the screen without leaving a trail
snake = [head]
snakelength = 3
score = 0
direction = 0
# Creating a turtle to draw the leaves
fruit = Turtle("circle", visible=False) # Create a turtle for the fruit
fruit.penup() # Raise the turtle's pen, allowing turtle to move around screen without leaving a trail
fruit.color("red")
# Add more turtles to display the text for the game and the score
writeturtle = Turtle(visible=False) # Create a new turtle for the text
writeturtle.write("Press SPACE to play!", align="center", font=MESSAGE_FONT)
# Add a score turtle
scoreturtledude = Turtle(visible=False) # Create a new turtle for the score
scoreturtledude.penup() # Disable turtle pen
x = screen.window_width() / 2 - 75 # 75 pixels from the right
y = screen.window_height() / 2 - 75 # And 75 pixels from the top
scoreturtledude.setpos(x, y) # Set the turtle's position
scoreturtledude.write('', align="right", font=SCORE_FONT)
screen.onkey(startgame, "space") # Bind space bar to startgame() so game will start when player presses space
screen.onkey(up, "Up") # Bind the up key to up()
screen.onkey(down, "Down") # Bind the down key to down()
screen.onkey(right, "Right") # Bind the right key to right()
screen.onkey(left, "Left") # Bind the left key to left()
screen.listen() # Allow the window to receive signals from the keyboard
screen.mainloop()
![enter image description here](https://i.stack.imgur.com/GPUCH.png)
У вас есть ряд проблем в вашем коде, например, малышам нравится, что за черепаха gameover()
имеет в виду, когда она делает t.hideturtle()
? Но два основных из них:
Перечитайте, что делает speed(0)
- вы неправильно поняли.
Вам нужно научиться писать лучшие комментарии. Это глупо:
fruit.color ("red") # Делаем фрукты красными
Это очень хорошо:
t.listen () # Функция прослушивания позволяет программе получать сигналы с клавиатуры