Lesson 20: Catch me if you can

posted May 8, 2019, 7:34 AM by Attila Lengyel   [ updated May 8, 2019, 8:10 AM ]
import turtle as t
t1 = t.Turtle()
t1.shape("turtle")
t1.fillcolor("blue")
t1.pencolor("blue")

t2 = t.Turtle()
screen = t.Screen()

def draw_rectangle(player, x, y, width, height, color):
startpos = player.pos()
startcolor = player.pencolor()
player.pencolor(color)
player.up()
player.goto(x, y)
player.down()
player.forward(width)
player.left(90)
player.forward(height)
player.left(90)
player.forward(width)
player.left(90)
player.forward(height)
player.left(90)
player.up()
player.goto(startpos)
player.down()
player.pencolor(startcolor)

draw_rectangle(t1, -210, -210, 420, 420, "red")

def inbox(player):
if player.xcor() >= 200:
player.up()
player.goto(199, player.ycor())
player.down()
return False
if player.xcor() <= -200:
player.up()
player.goto(-199, player.ycor())
player.down()
return False
if player.ycor() >= 200:
player.up()
player.goto(player.xcor(), 199)
player.down()
return False
if player.ycor() <= -200:
player.up()
player.goto(player.xcor(), -199)
player.down()
return False
return True

def f():
if inbox(t1): t1.forward(10)
def b():
if inbox(t1): t1.backward(10)
def l(): t1.left(10)
def r(): t1.right(10)
screen.onkey(f, "Up")
screen.onkey(b, "Down")
screen.onkey(l, "Left")
screen.onkey(r, "Right")

def catch():
if t1.distance(t2) < 10:
t2.write("CATCH!!!")
def f2():
if inbox(t2) : t2.forward(10)
catch()
def b2():
if inbox(t2): t2.backward(10)
catch()
def l2(): t2.left(10)
def r2(): t2.right(10)

screen.onkey(f2, "s")
screen.onkey(b2, "x")
screen.onkey(l2, "z")
screen.onkey(r2, "c")
screen.listen()
Comments