Lesson 20: Catch me if you can

posted May 10, 2019, 7:41 AM by Attila Lengyel   [ updated May 10, 2019, 8:04 AM ]
import turtle as t

player1 = t.Turtle()
player1.shape("turtle")
player1.pencolor("white")
player1.fillcolor("blue")

player2 = t.Turtle()
player2.shape("turtle")
player2.fillcolor("red")
player2.pencolor("white")
player2.goto(-180, 180)

speed = 10
angle = 10
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(player1, -210, -210, 420, 420, "black")

def position(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

import math
def catch(playera, playerb):
x1 = playera.xcor()
y1 = playera.ycor()
x2 = playerb.xcor()
y2 = playerb.ycor()

c = math.pow(x1-x2,2) + math.pow(y2-y1,2)
c = math.sqrt(c)
if c < 10:
playera.fillcolor("red")
playerb.fillcolor("blue")
def f():
if position(player1): player1.forward(speed)
def b():
if position(player1): player1.backward(speed)
def r(): player1.right(angle)
def l(): player1.left(angle)

screen.onkey(f, "Up")
screen.onkey(b, "Down")
screen.onkey(r, "Right")
screen.onkey(l, "Left")

def f2():
if position(player2): player2.forward(speed)
catch(player1, player2)
def b2():
if position(player2): player2.backward(speed)
catch(player1, player2)
def r2(): player2.right(angle)
def l2(): player2.left(angle)

screen.onkey(f2, "q")
screen.onkey(b2, "a")
screen.onkey(r2, "x")
screen.onkey(l2, "z")
screen.listen()
Comments