0

I'm trying to check if the chaser turtle collides with the runner turtle, but every time the chaser turtle get's close to the runner turtle, the print("Collision") never executes.

#   import relevant modules
from cProfile import run
from secrets import choice
import turtle as trtl
import random as rand

#   create variables for turtle player controller
moveAmount = 1

#   create variables for turtle finish line
runnerLocactionX = rand.randint(600, 900)
runnerLocactionY = rand.randint(-450 ,450)
turtleColors = ["red", "blue", "green", "orange", "purple", "gold"]


#   initialize Turtle player controller
chaser = trtl.Turtle(shape="square")
chaserLocationX = rand.randint(-600, 600)
chaserLocationY = rand.randint(-450 ,450)
chaserInitialLocation = (chaserLocationX, chaserLocationY)
chaser.penup()
chaser.goto(chaserInitialLocation)
chaser.pendown()

#   initialize runner
runner = trtl.Turtle(shape="square")
runner.pencolor(rand.choice(turtleColors))
runner.fillcolor(rand.choice(turtleColors))
runner.penup()
runner.goto(runnerLocactionX, runnerLocactionY)
runner.setheading(90)

#  Event handlers for changing direction
def goUp():
    chaser.setheading(90)
def goDown():
    chaser.setheading(270)
def goLeft():
    chaser.setheading(180)
def goRight():
    chaser.setheading(0)

def movechaser():
    chaser.forward(moveAmount)

#  Event handlers for collision detection 

def is_collided_with(a, b):
    return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10

def Collision():
    if is_collided_with(chaser, runner):
        print("Collision")
    else:
        print("No Collision!")

#   listen for events
wn = trtl.Screen()
wn.onkeypress(goUp, 'Up')
wn.onkeypress(goDown, 'Down')
wn.onkeypress(goLeft, 'Left')
wn.onkeypress(goRight, 'Right')
wn.onkeypress(movechaser, 'w')
wn.listen()

Collision()

wn.mainloop()

I've tried checking the distance, but the program closes after running. Also, I tried getting rid of the abs on both xcor and ycor, but nothing changed.

#  Event handlers for collision detection 
collision = turtle.Turtle()

collision.hideturtle()

if chaser.distance() == runner.distance():

    collision.goto(0,0)

    collision.showturtle()

    collision.write("COLLISION")
WeegeeDev
  • 1
  • 1
  • You only check collision one time when the app starts, then never check it again. Try calling it inside `movechaser()`. – ggorlen Nov 20 '22 at 17:16

0 Answers0