好吧,下面这段代码的目标本质上是确保可以使用箭头键向任何方向移动的乌龟无法进入盒子。我通过为我的类形状创建一个碰撞方法来做到这一点,并使用简单的数学来确保海龟无法进入该形状。然而遗憾的是,这不起作用,乌龟可以从除底部以外的各个方向进入形状。有人可以修复我的代码或帮助我以不同且更简单的方式解决此问题吗?非常感谢,这是我的代码:
import turtle
sam=turtle.Turtle()
score=turtle.Turtle()
screen=turtle.Screen()
screen.delay(0)
PEN_SIZE = 10
CURSOR_SIZE = 20
BOUNDARY = PEN_SIZE/2 + CURSOR_SIZE/2
sam.pensize(PEN_SIZE)
sam.speed('fastest')
sam.penup()
sam.goto(-400,-400)
sam.pendown()
sam.speed(0)
sam.color("blue")
screen.bgcolor("black")
class lshape4:
def __init__(self,turtle, x, y, width, height):
self.turtle=turtle
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self):
for i in range(2):
self.turtle.fd(self.width)
self.turtle.rt(90)
self.turtle.fd(self.height)
self.turtle.rt(90)
def collision(self, position):
x, y = position
left_boundary = self.x - self.width / 2
right_boundary = self.x + self.width / 2
bottom_boundary = self.y - self.height / 2
top_boundary = self.y + self.height / 2
if left_boundary <= x <= right_boundary and bottom_boundary <= y <= top_boundary:
return True
else:
return False
shapes = []
shape4 = lshape4(sam,-120,-270,100,20)
sam.penup()
sam.goto(-120, -270)
sam.lt(90)
sam.pendown()
shape4.draw()
shapes.append(shape4)
j = turtle.Turtle()
j.shape('turtle')
j.color('yellow')
j.penup()
j.goto(400, -370)
def right():
j.rt(90)
def left():
j.left(90)
def up():
j.forward(10)
position = j.position()
for shape in shapes:
if shape.collision(position):
j.undo()
return
def down():
j.bk(10)
position = j.position()
for shape in shapes:
if shape.collision(position):
j.undo()
return
screen.listen()
screen.onkeypress(up, 'Up')
screen.onkeypress(down, 'Down')
screen.onkeypress(right, 'Right')
screen.onkeypress(left, 'Left')
我建议对 up() 和 down() 函数进行以下更正:
def up():
j.forward(10)
position = j.position()
for shape in shapes:
if shape.collision(position):
j.undo()
while shape.collision(j.position()): # Undo until the top boundary clears the obstacle
j.undo()
return
def down():
j.backward(10)
position = j.position()
for shape in shapes:
if shape.collision(position):
j.undo()
while shape.collision((j.xcor(), j.ycor() - 10)): # Undo until the bottom boundary clears the obstacle
j.undo()
return