Держать черепаху внутри квадрата, без выходных и без ошибок - PullRequest
1 голос
/ 14 апреля 2019

Я хотел, чтобы черепаха не выходила из квадрата

окно выходит, без ошибок, но загрузка сохраняется, и если я нажимаю на окно, оно закрывается.

  • x, y - местоположение черепахи.
  • D - показывает погоду или нет, черепаха находится внутри квадрата и на линии (?).
  • a - ничто

    1. изменение направления
    2. изменение скорости
    3. проверка местоположения и изменение
    4. если черепаха стоит на одной линии, она идет вдоль границы.
import turtle
import msvcrt

turtle.setup(100, 100, 0, 0)
t = turtle.Turtle()
D = 0
a = 1

while True:
    if msvcrt.kbhit():
        c = msvcrt.getch().decode('UTF - 8')
        if c == 'j': # turn left
            t.left(10)
        if c == 'k':
            t.right(10)
        if c == 'a':# speed change
            a += 1
            if a > 10: # speed limitation
                a = 10
        if c == 'z':
            a += -1
            if a < 0:
                a = 0
    #---------------------------------------
    x = t.xcor() # turtle's location
    y = t.ycor()
    if x > 100: # if go out of square, go back to the square
        t.setx(100)
    if x < -100:
        t.setx(-100)
    if y > 100:
        t.sety(100)
    if y < -100:
        t.sety(-100)
    #---------------------------------------
    x = t.xcor() # turtle's location
    y = t.ycor()
    h = t.heading() # turtle's direction
    #---------------------------------------
    if - 100 < x < 100 and -100 < y < 100:
        D = 0 # if it's in the square, D = 0
    elif x == 100 and -100 < y < 100: # if it's in ~
        if 0 <= d <= 90: # direction changes
            t.setheading(90) # direction change to 90 degrees
            D = 1 # D = 1
        elif 270 <= d < 360:
            t.setheading(270)
            D = 2
    elif x == -100 and -100 < y < 100:
        if 90 <= d < 180:
            t.setheading(90)
            D = 2
        elif 180 <= d <= 270:
            t.setheading(270)
            D = 1
    elif y == 100 and -100 < x < 100:
        if 0 <= d < 90:
            t.setheading(0)
            D = 2
        elif 90 <= d <= 180:
            t.setheading(180)
            D = 1
    elif y == -100 and -100 < x < 100:
        if 180 <= d < 270:
            t.setheading(180)
            D = 2
        elif 270 <= d < 360:
            t.setheading(0)
            D = 1
    elif D == 1:
        t.left(90)
    elif D == 2:
        t.right(90)

1 Ответ

1 голос
/ 14 апреля 2019

Этот код беспорядок.Во-первых, установив размер окна на 100 x 100, а затем переместив вашу черепаху между -100 и 100 в обоих измерениях, вы увидите только 1/4 вашего поля игры!Зачем использовать модуль msvcrt, если в turtle встроены отличные события клавиатуры?Насколько я могу судить, ваш код проверяет и исправляет положение черепахи, но фактически никогда не перемещает его!И у вас есть петля while True:, которой нет места в управляемой событиями среде, такой как черепаха.

Давайте начнем с простого примера движения внутри квадрата, которым можно манипулировать с помощью клавиатуры:

from turtle import Screen, Turtle

def turn_left():
    turtle.left(10)

def turn_right():
    turtle.right(10)

def speed_up():
    speed = turtle.speed() + 1

    if speed > 10: # speed limitation
        speed = 10

    turtle.speed(speed)

def slow_down():
    speed = turtle.speed() - 1

    if speed < 1: # speed limitation
        speed = 1

    turtle.speed(speed)

def move():
    # there are two different senses of 'speed' in play, we'll exploit
    #  both!  I.e. as we move faster, we'll draw faster and vice versa
    turtle.forward(turtle.speed())

    # if we go out of square, go back into the square
    if not -100 < turtle.xcor() < 100:
        turtle.undo()
        turtle.setheading(180 - turtle.heading())
    elif not -100 < turtle.ycor() < 100:
        turtle.undo()
        turtle.setheading(360 - turtle.heading())

    screen.ontimer(move, 100)

screen = Screen()
screen.setup(300, 300)

# show turtle's boundary
boundary = Turtle('square', visible=False)
boundary.color('pink')
boundary.shapesize(10)
boundary.stamp()

turtle = Turtle()

move()

screen.onkey(turn_left, 'j')
screen.onkey(turn_right, 'k')
screen.onkey(speed_up, 'a')
screen.onkey(slow_down, 'z')

screen.listen()
screen.mainloop()

enter image description here

...