Как в python turtle сделать реакцию когда черепаха трогает край полотна tkinter?

Как в python turtle сделать реакцию когда черепаха трогает край полотна tkinter?
у меня небольшая игра "черепаха":
игра черепаха

from tkinter import *
from tkinter.messagebox import *
from tkinter import filedialog as fd
from tkinter import *
from tkinter import messagebox as mb
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import filedialog as fd
import tkinter.simpledialog
from tkinter import colorchooser
from PIL import ImageGrab
import keyboard
import turtle as red
import time
import ctypes
myappid = 'mycompany.myproduct.subproduct.version'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
root = Tk()
root.resizable(0, 0)
root.iconbitmap(r"C:\\turtle.ico")
global окно_управления
окно_управления = Toplevel(root)
окно_управления.iconbitmap(r"C:\\turtle.ico")
root.title("черепаха-гра")
canvas = Canvas(root, width=500, height=500)
canvas.grid()
turtle = red.RawTurtle(canvas)
turtle.shape("turtle")
global size
size = 5
turtle.pensize(5)
turtle.color("#307826")
canvas.configure(background="#91b6ed")
turtle.speed(6)
global цвета
global цвет
цвета = ["#4a2626", "blue", "red", "#307826"]
цвет = 3
global удар1
удар1 = False
global удар2
удар2 = False
global удар3
удар3 = False
global удар4
удар4 = False
def left(evt):
    print("left")
    turtle.left(45)
    print(turtle.heading())
def forward(evt):
    global удар1
    global удар2
    global удар3
    global удар4
    if turtle.position()[0] >= 220:
        if turtle.heading() == 45.0 or turtle.heading() == 0.0 or turtle.heading() == 315.0:
            print("block right")
            удар1 = True
            удар2 = False
        else:
            удар1 = False
    elif turtle.position()[0] <= -220:
        if turtle.heading() == 135.0 or turtle.heading() == 180.0 or turtle.heading() == 225.0:
            print("block left")
            удар2 = True
            удар1 = False
        else:
            удар2 = False
    elif turtle.position()[1] <= -220:
        if turtle.heading() == 315.0 or turtle.heading() == 270.0 or turtle.heading() == 225.0:
            print("block down")
            удар3 = True
            удар4 = False
        else:
            удар3 = False
    elif turtle.position()[1] >= 220:
        if turtle.heading() == 45.0 or turtle.heading() == 90.0 or turtle.heading() == 135.0:
            print("block up")
            удар4 = True
            удар3 = False
        else:
            удар4 = False
    print("x:" + str(turtle.position()[0]))
    print("y:" + str(turtle.position()[1]))
    print(str(удар1))
    print(str(удар2))
    print(str(удар3))
    print(str(удар4))
    print("удар1:" + str(удар1))
    print("удар2:" + str(удар2))
    print("удар3:" + str(удар3))
    print("удар4:" + str(удар4))
    if удар1 == False:
        print("up")
        turtle.forward(20)
    print("напрям:" + str(turtle.heading()))
def right(evt):
    print("right")
    turtle.right(45)
    print(turtle.heading())
def color(evt):
    print("новий колір!")
    новий_колір()
def reset(evt):
    print("ну, добре почистимо полотно...")
    turtle.reset()
    turtle.shape("turtle")
    turtle.pensize(5)
    turtle.color("#307826")
    canvas.configure(background="#91b6ed")
    turtle.speed(6)
def новий_колір():
    global цвета
    global цвет
    if цвет == 3:
        цвет = 0
    else:
        цвет += 1
    turtle.color(цвета[цвет])
def розмір_плюс(evt):
    global size
    size += 1
    print("більший розмір! тепер він дорівняє %s" %(size))
    turtle.pensize(size)
    time.sleep(0.1)
def розмір_мінус(evt):
    global size
    size -= 1
    print("менший розмір! тепер він дорівняє %s" %(size))
    turtle.pensize(size)
    time.sleep(0.1)
root.bind('<Right>', right)
root.bind('<Left>', left)
root.bind('<Up>', forward)
root.bind('<KeyPress-1>', reset)
root.bind('<KeyPress-2>', розмір_плюс)
root.bind('<KeyPress-3>', розмір_мінус)
root.bind('<space>', color)
root.mainloop()


и у меня возникла проблема когда черепаха трогает край полотна она находит то что она не трогает другого края и проходит через край в этом коде:
код

def forward(evt):
    global удар1
    global удар2
    global удар3
    global удар4
    if turtle.position()[0] >= 220:
        if turtle.heading() == 45.0 or turtle.heading() == 0.0 or turtle.heading() == 315.0:
            print("block right")
            удар1 = True
            удар2 = False
        else:
            удар1 = False
    elif turtle.position()[0] <= -220:
        if turtle.heading() == 135.0 or turtle.heading() == 180.0 or turtle.heading() == 225.0:
            print("block left")
            удар2 = True
            удар1 = False
        else:
            удар2 = False
    elif turtle.position()[1] <= -220:
        if turtle.heading() == 315.0 or turtle.heading() == 270.0 or turtle.heading() == 225.0:
            print("block down")
            удар3 = True
            удар4 = False
        else:
            удар3 = False
    elif turtle.position()[1] >= 220:
        if turtle.heading() == 45.0 or turtle.heading() == 90.0 or turtle.heading() == 135.0:
            print("block up")
            удар4 = True
            удар3 = False
        else:
            удар4 = False
    print("x:" + str(turtle.position()[0]))
    print("y:" + str(turtle.position()[1]))
    print(str(удар1))
    print(str(удар2))
    print(str(удар3))
    print(str(удар4))
    print("удар1:" + str(удар1))
    print("удар2:" + str(удар2))
    print("удар3:" + str(удар3))
    print("удар4:" + str(удар4))
    if удар1 == False:
        print("up")
        turtle.forward(20)
    elif удар2 == False:
        print("up")
        turtle.forward(20)
    elif удар3 == False:
        print("up")
        turtle.forward(20)
    elif удар4 == False:
        print("up")
        turtle.forward(20)
    print("напрям:" + str(turtle.heading()))


а первом коде он реагирует на правий край...
буду благодарен за ответ на вопрос!
(только за ответ который сработает в python 3.9)
  • Вопрос задан
  • 236 просмотров
Решения вопроса 1
@Ant69
Программирую в VB, JS, Python
Хорошо бы пересмотреть логику программы! Первое на что обратить внимание -
if удар1 == False:
print("up")
turtle.forward(20)

удар1 - переменная, разрешающая движение!
а удар2, удар3, удар4 - тоже нужно проверить
как то так..
if (удар1 == False) and (удар2 == False) and (удар3 == False) and (удар4 == False):

А потом разобраться с логикой
if turtle.position()[0] >= 220:
..
elif turtle.position()[0] <= -220:
..
elif turtle.position()[1] <= -220:
..
elif turtle.position()[1] >= 220:

посмотреть какие значения принимает turtle.position()[0] и turtle.position()[1] ( координаты черепашки) минимальные и максимальные и тд.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы