Reputation: 25
So I'm making a "game" where the turtle has to stay in the square, and if it moves out the game ends. I used the break command in a while loop, and in the instructional video provided with the assessment, it worked, but I can't get it too.If you're confused, I want the turtle to be unable to move when it goes out of the square. What can I do? Here is the code
import turtle
import random
turt = turtle.Turtle()
turt.speed("100")
tart = turtle.Turtle()
screen = turtle.Screen()
def up():
turt.setheading(90)
turt.forward(10)
def down():
turt.setheading(270)
turt.forward(10)
def left():
turt.setheading(180)
turt.forward(10)
def right():
turt.setheading(0)
turt.forward(10)
screen.onkey(up, "w")
screen.onkey(down, "s")
screen.onkey(left, "a")
screen.onkey(right, "d")
screen.listen()
tart.speed("100101001010000010101010000010010100")
tart.shape("square")
tart.penup()
tart.goto(-250,250)
tart.pendown()
for i in range(4):
tart.forward(400)
tart.right(90)
tart.forward(100)
tart.penup()
tart.goto(-2000000000,200000000000000000000)
while True:
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
turt.color(r,g,b)
if turt.ycor() > 250 or turt.xcor() > -250:
break
elif turt.xcor() > 250 or turt.ycor() < -250:
break
#----------------------------------
tart.speed("100101001010000010101010000010010100")
tart.shape("square")
tart.penup()
tart.goto(-400,300)
tart.pendown()
Upvotes: 0
Views: 591
Reputation: 41872
Your program has a number of mistakes and inconsistencies. Let's take it apart and put it back together as a proper turtle program. (No while True:
needed nor desired.)
from turtle import Pen, Turtle, Screen
def up():
turtle.setheading(90)
if turtle.ycor() < 240:
turtle.forward(10)
def down():
turtle.setheading(270)
if -240 < turtle.ycor():
turtle.forward(10)
def left():
turtle.setheading(180)
if -240 < turtle.xcor():
turtle.forward(10)
def right():
turtle.setheading(0)
if turtle.xcor() < 240:
turtle.forward(10)
turtle = Turtle()
turtle.speed('fastest')
pen = Pen()
pen.hideturtle()
pen.speed('fastest')
pen.penup()
pen.goto(-250, 250)
pen.pendown()
for _ in range(4):
pen.forward(500)
pen.right(90)
screen = Screen()
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.listen()
screen.mainloop()
I removed your questionable turtle color logic for simplicity as it had no bearing on your quesion.
Upvotes: 2