Lesson 18: Turtle in a box

posted May 3, 2019, 8:45 AM by Attila Lengyel   [ updated May 10, 2019, 7:28 AM ]
import turtle as t

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

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, "red")

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

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")

screen.listen()
Comments