How do I set screen boundaries so when the turtle reaches the edge it will stop or turn around
import turtle
t=turtle.Turtle()
s=turtle.Screen()
p=t.xcor()
p1=t.ycor()
x=300
y=300
s.setup(x,y)
t.color("white")
s.bgcolor("black")
def up():
player=False
while player==False:
t.speed(1)
t.fd(10)
def right():
t.speed(0)
t.right(90)
def left():
t.speed(0)
t.left(90)
s.onkey(up,"up")
s.onkey(right,"right")
s.onkey(left,"left")
s.listen()
I thought this would stop it at the edge of the screen
The code below isn't completely done but I didn't know what to change it to
while p and p1 != x and y:
t.right(90)
if p and p1 == x and y:
t.speed(0)
t.right(180)
-
in other graphic systems/modules when you have to move 100pixels then you do: move few pixel (ie. 2 pixels), check collisions (ie. with screen border), move few pixel again, check collisions again, etc. - so you run it in loop.furas– furas2017年11月29日 09:21:15 +00:00Commented Nov 29, 2017 at 9:21
2 Answers 2
I'm surprised your code works as 'up' isn't recognized as a valid keysym on my turtle system -- it has to be capitalized: 'Up'. Perhaps it's a Unix / Windows schism.
Rather than move one or two pixels at a time testing if you crossed the boundary, here's another approach. Move forward a reasonable amount, detect when you've crossed the boundary, undo that movement forward, turn around, redo your movement forward:
from turtle import Turtle, Screen
WIDTH, HEIGHT = 500, 500
DISTANCE = 10
screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')
turtle = Turtle()
turtle.speed('fastest')
turtle.color('white')
def up():
turtle.forward(DISTANCE) # try first and undo on error
x, y = turtle.position()
if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT / 2:
turtle.undo() # undo error
turtle.left(180) # turn around
turtle.forward(10) # redo movement but in new direction
def right():
turtle.right(90)
def left():
turtle.left(90)
screen.onkey(up, 'Up')
screen.onkey(right, 'Right')
screen.onkey(left, 'Left')
screen.listen()
screen.mainloop()
If you add any other movement functions, e.g. Down for moving backward, then move the boundary crossing logic into its own function and share that with all the movement commands.
Comments
Like furas said you'll need to move a couple pixels at a time in a loop and check for collision. I needed a similar function recently, here it is if you want to try it. I've never used python turtle.screen but I'm sure you could define the edges in a list, because I used this code in a for loop of lines it shouldn't touch.
def online(point,edge):
first = edge[0]
second = edge[1]
firstx = first[0]
firsty = first[1]
secondx = second[0]
secondy = second[1]
if firstx <= point[0] <= secondx and firsty >= point[1] >= secondy:
return(True)
elif firstx <= point[0] <= secondx and firsty <= point[1] <= secondy:
return(True)
elif firstx >= point[0] >= secondx and firsty >= point[1] >= secondy:
return(True)