Besides the sussy title (sorry I had no better way to put it) I'm doing a project where I have to keep bouncy balls bouncing in a square. This is my code (pls use the same turtle names)
import turtle
import random
turt = turtle.Turtle()
tart = turtle.Turtle()
screen = turtle.Screen()
turt.speed('fastest')
tart.speed('fastest')
turt.penup()
turt.goto(-250,250)
turt.pendown()
tart.penup()
tart.color("red")
tart.pensize(10)
tart.shape("circle")
for i in range(4):
turt.forward(450)
turt.right(90)
def up():
turt.setheading(90)
if turt.ycor() < 240:
tart.forward(1)
def down():
turt.setheading(270)
if -240 < tart.ycor():
tart.forward(1)
def left():
turt.setheading(180)
if -240 < turt.xcor():
tart.forward(1)
def right():
tart.setheading(0)
if turt.xcor() < 240:
tart.forward(1)
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.mainloop()
tart.right(
random.randint(1,359)
)
tart.pendown()
while True:
tart.forward(10)
I just want the ball to stop bouncing for now at the square
You have turt
and tart
names mixed up in the movement functions (better names would help!!) and the bounding coordinates are wrong. Below I also added a listen()
because as is the keys didn't work and increased the forward size because it was really slow.
import turtle
import random
turt = turtle.Turtle()
tart = turtle.Turtle()
screen = turtle.Screen()
turt.speed('fastest')
tart.speed('fastest')
turt.penup()
turt.goto(-250,250)
turt.pendown()
tart.penup()
tart.color("red")
tart.pensize(10)
tart.shape("circle")
for i in range(4):
turt.forward(450)
turt.right(90)
speed = 10
def up():
tart.setheading(90)
if tart.ycor() < 240:
tart.forward(speed)
def down():
tart.setheading(270)
if tart.ycor() > -190:
tart.forward(speed)
def left():
tart.setheading(180)
if tart.xcor() > -240:
tart.forward(speed)
def right():
tart.setheading(0)
if tart.xcor() < 190:
tart.forward(speed)
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.listen()
screen.mainloop()
tart.right(
random.randint(1,359)
)
tart.pendown()
while True:
tart.forward(10)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.