0

I am trying to draw a shape and then move that shape around the screen with the arrow keys. My goal is to make a 2D game in the end, but I can't figure out how to draw more than a circle and get it all to move.

I pasted my code so far. After the circle is drawn I tried going for a line and it doesn't seem to like that. If I take out that forward statement then I can move the circle around again.

import turtle

def Left():
  move.left(1)
  move.forward(1)

def Right():
  move.right(1)
  move.forward(1)

def Forwards():
  move.forward(1)

def Backwards():
  move.backward(1)

def moving_object(move):
    move.fillcolor('orange')
    move.begin_fill()
    move.circle(20)
    move.forward(10)
    move.end_fill()

screen = turtle.Screen()
screen.setup(600,600)
screen.bgcolor('green')
screen.tracer(0)

move = turtle.Turtle()
move.color('orange')
move.speed(0)
move.width(2)
move.hideturtle()
move.penup()
move.goto(-250, 0)
move.pendown()

screen.listen()
screen.onkeypress(Left, "Left")
screen.onkeypress(Right, "Right")
screen.onkeypress(Forwards, "Up")
screen.onkeypress(Backwards, "Down")

while True :
    move.clear()
    moving_object(move)
    screen.update()

martineau
  • 119,623
  • 25
  • 170
  • 301
Jake Henry
  • 49
  • 1
  • 1
  • 6

1 Answers1

1

The whole structure of your turtle code is incorrect. There shouldn't be a while True: in an event-driven world like turtle. Your looping logic made any forward motion inside moving_object() repeat infinitely and push your turtle off the screen.

Let's rebuild your program to exhibit tank-like movement where the circle is the tank and the line is its gun:

from turtle import Screen, Turtle

DIAMETER = 40

def left():
    turtle.left(15)
    moving_object(turtle)

def right():
    turtle.right(15)
    moving_object(turtle)

def forward():
    turtle.forward(5)
    moving_object(turtle)

def backward():
    turtle.backward(5)
    moving_object(turtle)

def moving_object(move):
    move.clear()

    move.begin_fill()
    move.dot(DIAMETER)  # dot makes position center of circle
    move.end_fill()

    move.forward(DIAMETER/2 + 25)
    move.backward(DIAMETER/2 + 25)  # return so we don't move object

    screen.update()

screen = Screen()
screen.setup(600, 600)
screen.bgcolor('green')
screen.tracer(0)

turtle = Turtle()
turtle.hideturtle()
turtle.color('orange')
turtle.width(5)

screen.onkeypress(left, 'Left')
screen.onkeypress(right, 'Right')
screen.onkeypress(forward, 'Up')
screen.onkeypress(backward, 'Down')
screen.listen()

moving_object(turtle)

screen.update()
screen.mainloop()
cdlane
  • 40,441
  • 5
  • 32
  • 81