The class "turtles" has no attribute "forward" (Python Turtle) - python

I am trying to make a turtle race, but I get an error that the class "turtles" has no attribute "forward". Here is my code:
class turtles:
def __init__(self, color, posX):
self = turtle.Turtle(shape='turtle', visible=False)
self.color(color)
self.penup()
self.shape('turtle')
self.goto(posX, -300)
self.showturtle()
self.setheading(90)
def start_race(self):
self.forward(random.randrange(0,10))
t1 = turtles('red',-150)
t2 = turtles('orange', -100)
t3 = turtles('yellow',-50)
t4 = turtles('green', 0)
t5 = turtles('light blue', 50)
t6 = turtles('blue',100)
t7 = turtles('purple', 150)
def begin_race():
t1.start_race()
t2.start_race()
t3.start_race()
t4.start_race()
t5.start_race()
t6.start_race()
t7.start_race()
begin_race()

Replace your turtles class with this:
class turtles(turtle.Turtle):
def __init__(self, color, posX):
self.color(color)
self.penup()
self.shape('turtle')
self.goto(posX, -300)
self.showturtle()
self.setheading(90)
def start_race(self):
self.forward(random.randrange(0,10))
Inheritance in Python is done by specifying a class in brackets after declaring a class name.
In this case, your turtles class inherits from the turtle.Turtle class and then has its attributes changed. Seems there was also some repetition with specifying the turtle's colour and visibility (I removed that for you)

The reason you get this error is because there is no attribute (i.e. a variable or method) called forward in your turtles class. The forward method is part of the turtle.Turtle class. You could solve this in different ways:
Method 1: using inheritance
You could derive your turtles class from the existing turtle.Turtle class. To do that, you should make the following changes:
The class turtles should be defined as class turtles(turtle.Turtle) to derive from it.
In the __init__() method you should not reassign self, because this is a reference to the actual object that's being initialized.
You should call the __init__() method of the original Turtle class.
So the full code could be like below. I renamed start_race() to advance_race() because that better describes what it does. And I added an infinite loop so you'll see the turtles "racing". This is just for demonstration, of course.
import random
import turtle
class turtles(turtle.Turtle):
def __init__(self, color, posX):
super().__init__(shape='turtle', visible=False)
self.color(color)
self.penup()
self.goto(posX, -300)
self.showturtle()
self.setheading(90)
def advance_race(self):
self.forward(random.randrange(0,10))
t1 = turtles('red', -150)
t2 = turtles('orange', -100)
t3 = turtles('yellow', -50)
t4 = turtles('green', 0)
t5 = turtles('light blue', 50)
t6 = turtles('blue', 100)
t7 = turtles('purple', 150)
while True:
t1.advance_race()
t2.advance_race()
t3.advance_race()
t4.advance_race()
t5.advance_race()
t6.advance_race()
t7.advance_race()
Method 2: using a wrapper class
Alternatively, you could create a new class that "holds" a turtle object. Using this method, you should store the turtle "inside" self and access it as self.turtle (or any other name).
class turtles:
def __init__(self, color, posX):
self.turtle = turtle.Turtle(shape='turtle', visible=False)
self.turtle.color(color)
self.turtle.penup()
self.turtle.goto(posX, -300)
self.turtle.showturtle()
self.turtle.setheading(90)
def advance_race(self):
self.turtle.forward(random.randrange(0,10))
(rest of the code same as above)

Related

creating boxes using turtle

can someone please help me making few boxes, each on different axis co-ordinates using turtle,
P.S. trying to use class and objects in below code:
import turtle
from turtle import *
# window:
window = turtle.Screen()
window.bgcolor("white")
window.title("Process flow")
class a:
penup()
shape("square")
speed(0)
def __init__(self, reshape, color, location):
self.reshape = reshape
self.color = color
self.location = location
start_node1 = a(reshape=shapesize(stretch_wid=1, stretch_len=3), color=color("light blue"), location=goto(0, 300))
start_node2 = a(reshape=shapesize(stretch_wid=1, stretch_len=3), color=color("yellow"), location=goto(0, 270))
print(start_node1)
print(start_node2)
done()
You seem to have strung together random bits of code with the hope that it would work. E.g. argument calls like:
..., location=goto(0, 300)
pass None onto your initializer as that's what goto() returns. And importing turtle two different ways:
import turtle
from turtle import *
is a sign you're in conceptual trouble. Below is my rework of your code to display boxes of different colors and sizes at various locations that tries to retain as much of the "flavor" of your original code as possible:
from turtle import Screen, Turtle
class Box(Turtle):
def __init__(self, reshape, color, location):
super().__init__(shape='square', visible=False)
self.shapesize(**reshape)
self.color(color)
self.speed('fastest')
self.penup()
self.goto(location)
self.showturtle()
screen = Screen()
screen.title("Process flow")
start_node1 = Box(reshape={'stretch_wid':1, 'stretch_len':3}, color='light blue', location=(100, 300))
start_node2 = Box(reshape={'stretch_wid':2, 'stretch_len':4}, color='yellow', location=(-100, 270))
screen.exitonclick()

Creating Turtle objects in a class with python

I am trying to create turtle objects with a class for my project which is a game. Each "Plane" object consists of:
plane3 = RawTurtle(screen)
plane3.ht()
plane3.color("red")
plane3.shape("plane.gif")
plane3.penup()
plane3.speed('fastest')
plane3.setposition(-270, 200)
plane3.setheading(360)
When putting this into a class and looking at other stack overflows questions to find out what to do, i threw together the following code:
class planes():
def __init__(self):
self.RawTurtle = RawTurtle(screen)
#self.hideturtle()
self.color = "red"
self.shape = ("plane.gif")
#self.penup()
self.speed = "fastest"
self.setposition = (-270, 100)
self.setheading = 360
Plane4 = planes()
When the code is run the turtle takes no shape or colour and is just a black triangle even though it causes no errors. However, errors do occur with the plane.hideturtle and plane.penup() functions which is why they are commented out.
File "C:/Users/marco/Desktop/Trooper shooter/TrooperShooter.py", line 694, in init
self.hideturtle()
AttributeError: 'planes' object has no attribute 'hideturtle'
Planes outside the class work perfectly and all planes are exactly identical. Any help is appreciated!
hideturtle() and penup() are both methods for the RawTurtle class, you haven't defined them for your planes class. So instead of this:
self.hideturtle()
self.penup()
you should have this:
self.RawTurtle.hideturtle()
self.RawTurtle.penup()
I believe your real problem is that your designed your plane class such that it has a turtle instead of designing it such that it is a turtle.
Taking the has a approach, every time you want to enable some additional turtle feature on your plane, you have to add a method to pass the call through to the contained turtle. Taking the is a approach, all turtle methods are in play:
from turtle import RawTurtle, TurtleScreen
from tkinter import Tk, Canvas, RIGHT
class Plane(RawTurtle):
def __init__(self):
super().__init__(screen)
self.hideturtle()
self.color('red')
self.shape('plane.gif')
# self.speed('fastest') # commented out while debugging
self.penup()
self.setposition(-270, 100)
self.setheading(0)
self.showturtle()
root = Tk()
canvas = Canvas(root, width=600, height=400)
canvas.pack(side=RIGHT)
screen = TurtleScreen(canvas)
screen.register_shape('plane.gif')
plane4 = Plane()
plane4.forward(400)
screen.mainloop()

How can I move turtles created in a different function in Python?

I'm very new to working with python and coding in general but I've been playing around with turtle for the past couple of days. I'm trying to create several functions where other functions move a turtle created within a different function. For instance:
import turtle as t
def setUp():
t.setup(900,600)
t.colormode(255)
win = t.Screen()
def turtles():
t1 = t.Turtle()
t1.shapesize(1.5,1.5,0)
t1.color('red')
t1.pensize(3)
t1.shape('turtle')
def moveTurtle():
t1.forward(50)
setUp()
turtles()
moveTurtle()
In my example here when python gets down to moveTurtles(), t1 isn't recognized due to it having been created in a previous function. If anyone could give me some insight into how I could go about doing this I'd really appreciate it. Thank you!
You have 2 options:
option 1:
return variable from first method and send it to second method:
import turtle as t
def setUp():
t.setup(900,600)
t.colormode(255)
win = t.Screen()
def turtles():
t1 = t.Turtle()
t1.shapesize(1.5,1.5,0)
t1.color('red')
t1.pensize(3)
t1.shape('turtle')
return t1
def moveTurtle(t1):
t1.forward(50)
setUp()
moveTurtle(turtles())
option 2:
Using global variable which is not recommended but usable:
import turtle as t
t1 = None
def setUp():
t.setup(900,600)
t.colormode(255)
win = t.Screen()
def turtles():
global t1
t1 = t.Turtle()
t1.shapesize(1.5,1.5,0)
t1.color('red')
t1.pensize(3)
t1.shape('turtle')
def moveTurtle():
t1.forward(50)
setUp()
turtles()
moveTurtle()
option 3:
Turtles, and the screen object, are global entities by design of the turtle package. (A turtle local to a function doesn't get reclaimed when the function returns.) Simply make them global, and access them globally or pass them to where they're needed:
from turtle import Screen, Turtle
def setUp(w):
w.setup(900, 600)
w.colormode(255)
def turtles(t):
t.shapesize(1.5, 1.5, 0)
t.color('red')
t.pensize(3)
t.shape('turtle')
def moveTurtle(t):
t.forward(50)
win = Screen()
t1 = Turtle()
setUp(win)
turtles(t1)
moveTurtle(t1)

Filling a shape with color in python turtle

I'm trying to fill a shape with a color but when I run it, it does not show.
Am I not supposed to use classes for this? I am not proficient with python-3 and still learning how to use classes
import turtle
t=turtle.Turtle()
t.speed(0)
class Star(turtle.Turtle):
def __init__(self, x=0, y=0):
turtle.Turtle.__init__(self)
self.shape("")
self.color("")
#Creates the star shape
def shape(self, x=0, y=0):
self.fillcolor("red")
for i in range(9):
self.begin_fill()
self.left(90)
self.forward(90)
self.right(130)
self.forward(90)
self.end_fill()
#I was hoping this would fill the inside
def octagon(self, x=0.0, y=0.0):
turtle.Turtle.__init__(self)
def octa(self):
self.fillcolor("green")
self.begin_fill()
self.left(25)
for x in range(9):
self.forward(77)
self.right(40)
#doesn't run with out this
a=Star()
Issues with your program: you create and set the speed of a turtle that you don't actually use; turtle.py already has a shape() method so don't override it to mean something else, pick a new name; you don't want the begin_fill() and end_fill() inside the loop but rather surrounding the loop; you call your own shape() method with invalid arguments.
The following rework of your code addresses the above issues:
from turtle import Turtle, Screen
class Star(Turtle):
def __init__(self, x=0, y=0):
super().__init__(visible=False)
self.speed('fastest')
self.draw_star(x, y)
def draw_star(self, x=0, y=0):
""" Creates the star shape """
self.penup()
self.setposition(x, y)
self.pendown()
self.fillcolor("red")
self.begin_fill()
for _ in range(9):
self.left(90)
self.forward(90)
self.right(130)
self.forward(90)
self.end_fill()
t = Star()
screen = Screen()
screen.exitonclick()

Returning value when instance "called"

I want a certain function callable on a class. Something similar to:
class foo():
def __init__(self):
self.img = pygame.Surface((20, 20))
def magicfunction(self):
return self.img
bar = foo()
screen = pygame.display.set_mode((200, 200))
screen.blit(bar)
Which magic-function do I have to use?
If I understand you correctly, you want to create a class of your own, which is also a surface. That sounds exactly like inheritance! Try making foo a child of pygame.Surface:
class foo(pygame.Surface):
def __init__(self):
pygame.Surface.__init__(self, (20, 20))
more_data = "You should be able to extend this class freely"

Categories

Resources