Reputation: 49
When I run the program it freezes up and doesn't work. The point of the program is to print something out when the x and y position coordinates of the user controlled turtle which is controlled by key-bindings is less then 10 pixels from the other turtle x and y position coordinates.
import turtle
import random
wn = turtle.Screen()
wn.setup(width = 450, height = 450)
player = turtle.Turtle()
player2 = turtle.Turtle()
def up():
y = player.ycor()
y = y + 5
player.sety(y)
if y>=310:
player.sety(y-15)
def down():
y = player.ycor()
y = y - 5
player.sety(y)
if y<-310:
player.sety(y+15)
def left():
x = player.xcor()
x = x - 5
player.setx(x)
if x<=-625:
player.setx(x+15)
def right():
x = player.xcor()
x = x + 5
player.setx(x)
if x>=625:
player.setx(x-15)
player.penup()
player.setpos(0,0)
player.showturtle()
player.shape("square")
wn.bgcolor("green")
player2.shape("square")
player2.penup()
player2.setpos(300,300)
player2.showturtle()
turtle.listen()
turtle.onkeypress(up,"Up")
turtle.onkeypress(left,"Left")
turtle.onkeypress(right,"Right")
turtle.onkeypress(down, "Down")
def checkcollision(player,player2):
if abs(player.xcor() - player2.xcor()) < 10 and abs(player.ycor() - player2.ycor()) < 10:
player.write("collision")
while True:
checkcollision(player,player2)
Upvotes: 2
Views: 67
Reputation: 3355
I think it freezes because of the loop in your code:
while True:
checkcollision(player,player2)
It's always checking the collision, move that code to the movement functions Up
, Down
, Left
, Right
etc and then call it after doing the movement.
Upvotes: 3