The goal of this code down below is essentially to make sure the turtle which can move in any direction using the arrow key cannot enter the box. I did this by making a collision method for my class shape and used simple math to ensure the turtle cannot enter the shape.
However sadly it doesn't work. The turtle can enter the shape from every direction except the bottom.
Can someone either fix my code or help me go about this in a different and easier way?
Here is my code:
import turtlesam=turtle.Turtle()score=turtle.Turtle()screen=turtle.Screen()screen.delay(0)PEN_SIZE = 10CURSOR_SIZE = 20BOUNDARY = PEN_SIZE/2 + CURSOR_SIZE/2sam.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 Falseshapes = []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() returndef 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')