Python (Turtle) Remove turtle / arrow - python

I am trying to make a basic Pong and I don't understand why the arrow/turtle in the middle of the screen displays.
The paddle on the screen consists of 6x turtle objects stored in self.paddle.
I know the problem has something to do with the p = Paddle() but I don't understand where the arrow-object is since it seems to not be in the list mentioned above (print(self.paddle)).
Can someone enlighten me?
from turtle import Turtle, Screen
screen = Screen()
screen.setup(width=1000, height=700)
class Paddle(Turtle):
def __init__(self):
super().__init__()
self.paddle = []
self.create_player_paddle()
def create_player_paddle(self):
for pad in range(0, 6):
x = -480
y = 30
p = Turtle(shape="square")
p.turtlesize(0.5)
p.penup()
p.goto(x, y)
self.paddle.append(p)
for part in range(len(self.paddle)):
self.paddle[part].goto(x, y)
y -= 10
p = Paddle()
screen.update()
screen.exitonclick()

I don't understand where the arrow-object is since it seems to not be
in the list mentioned above ... Can someone enlighten me?
Normally, a class like Paddle() either isa Turtle or contains one or more instances of Turtle. But you've done both, it is both a Turtle (the source of your mystery arrow) and it contains a list of turtles. The simple fix is to remove Turtle as its superclass and remove the super().__init__() code:
class Paddle():
def __init__(self):
self.paddle = []
self.create_player_paddle()
Below is my rework of your code addressing the above and other issues I saw:
from turtle import Turtle, Screen
class Paddle():
def __init__(self):
self.segments = []
self.create_player_paddle()
def create_player_paddle(self):
x = -480
y = 30
for _ in range(6):
segment = Turtle(shape='square')
segment.turtlesize(0.5)
segment.penup()
segment.goto(x, y)
self.segments.append(segment)
y -= 10
screen = Screen()
screen.setup(width=1000, height=700)
paddle = Paddle()
screen.exitonclick()
The usual approach to a Pong game in turtle is to make the paddle a subclass of Turtle and then use shapesize() to stretch the turtle to be the rectangle you desire. But this has issues with collision detection. Your approach makes the paddle somewhat more complicated, but might work better collision-detection-wise as you can test each segment.

if you need to hide the Turtle pointer, put Turtle.hideturtle(self) in your constructor init function

Related

Python turtle module

I'm currently new to python programming. Nowadays I'm building a snake game using the turtle module. I want to refresh the screen after every piece of snake object parts has moved. So I turned off the tracer and use the update function after the for loop.
But to do that I must import the time module and use the time.sleep() function.If I don't use it the python turtle module begins to not respond. I want to know what is the reason why I must use the time function and why I can't simply use sc.update directly without time function.
here is my code
from turtle import *
from snake import *
import time
sc = Screen()
sc.bgcolor('black')
sc.setup(width=600, height=600)
sc.tracer(0)
# diyego is our snake name
diyego = Snake(10)
run = 1
while run:
#here is the problem
sc.update()
time.sleep(1) #used time.sleep
for i in range(len(diyego.snake_object_list)-1, 0, -1):
infront_item_position = diyego.snake_object_list[i - 1].pos()
diyego.snake_object_list[i].goto(infront_item_position)
diyego.snake_head.forward(10)
sc.exitonclick()
#Snake module
from turtle import *
class Snake():
def __init__(self, number_of_parts):
"""Should pass the lenght of snake"""
self.snake_object_list = []
self.create_snake_parts(number_of_parts)
self.snake_head = self.snake_object_list[0]
def create_snake_parts(self, number_of_parts):
""" Get number of parts which snake shuld have and create snake it"""
x_cor = 0
for i in range(number_of_parts):
snake = Turtle()
snake.speed(0)
snake.shape("circle")
snake.color('white')
snake.penup()
snake.setx(x=x_cor)
self.snake_object_list.append(snake)
x_cor += -20
I just want to know why the turtle gets not respond when I remove the time.sleep()
What you describe is possible, but the problem isn't lack of use of the sleep() function but rather your use of (effectively) while True: which has no place in an event-driven world like turtle. Let's rework your code using ontimer() events and make the snake's basic movement a method of the snake itself:
from turtle import Screen, Turtle
CURSOR_SIZE = 20
class Snake():
def __init__(self, number_of_parts):
""" Should pass the length of snake """
self.snake_parts = []
self.create_snake_parts(number_of_parts)
self.snake_head = self.snake_parts[0]
def create_snake_parts(self, number_of_parts):
""" Get number of parts which snake should have and create snake """
x_coordinate = 0
for _ in range(number_of_parts):
part = Turtle()
part.shape('circle')
part.color('white')
part.penup()
part.setx(x_coordinate)
self.snake_parts.append(part)
x_coordinate -= CURSOR_SIZE
def move(self):
for i in range(len(self.snake_parts) - 1, 0, -1):
infront_item_position = self.snake_parts[i - 1].position()
self.snake_parts[i].setposition(infront_item_position)
self.snake_head.forward(CURSOR_SIZE)
def slither():
diyego.move()
screen.update()
screen.ontimer(slither, 100) # milliseconds
screen = Screen()
screen.bgcolor('black')
screen.setup(width=600, height=600)
screen.tracer(0)
diyego = Snake(10)
slither()
screen.exitonclick()

Trying to create two objects at the same time but it creates one

I'm trying to develop a simple game while I'm learning python. Game is not complex, random cars (which are squares) are spawning at right of the screen and they are going to left. We are a turtle, trying to avoid them and make it to the top of the screen.
The problem is my code below doesn't spawn two objects at the same time, it spawns just one.
from turtle import Screen
from turt import Turt
from spawnpoint import SpawnPoint
from cars import Car
import random
screen = Screen()
screen.setup(1000, 700)
screen.title("Cars and Turtle")
screen.bgcolor("gray")
turt = Turt()
is_game_on = True
screen.listen()
screen.onkey(turt.move_up, "Up")
spawn_points_ycords = [300, 200, 100, 0, -100, -200]
spawn_1 = SpawnPoint(spawn_points_ycords[0])
spawn_2 = SpawnPoint(spawn_points_ycords[1])
spawn_3 = SpawnPoint(spawn_points_ycords[2])
spawn_4 = SpawnPoint(spawn_points_ycords[3])
spawn_5 = SpawnPoint(spawn_points_ycords[4])
spawn_6 = SpawnPoint(spawn_points_ycords[5])
spawn_points = [spawn_1, spawn_2, spawn_3, spawn_4, spawn_5, spawn_6]
while is_game_on:
for n in range(60):
if n == 59:
random_spawn = spawn_points[random.randint(0, len(spawn_points)-1)]
random_spawn_2 = spawn_points[random.randint(0, len(spawn_points)-1)]
while random_spawn_2 == random_spawn:
random_spawn_2 = spawn_points[random.randint(0, len(spawn_points) - 1)]
random_spawn_car = Car(random_spawn.spawn.ycor())
random_spawn_2_car = Car(random_spawn_2.spawn.ycor())
screen.exitonclick()
My spawn points class code:
from turtle import Turtle
class SpawnPoint:
def __init__(self, ycor):
self.spawn = Turtle()
self.spawn.hideturtle()
self.spawn.speed(0)
self.spawn.penup()
self.spawn.goto(600, ycor)
self.spawn.showturtle()
self.new_car = None
and my car class code:
from turtle import Turtle
import random
class Car:
def __init__(self, ycor):
self.body = Turtle()
self.body.hideturtle()
self.body.penup()
self.body.shape("square")
self.colors = ["black", "red", "orange", "blue", "green", "yellow"]
self.body.color(self.colors[random.randint(0, len(self.colors)-1)])
self.body.shapesize(1, 5, 0)
self.body.speed(2)
self.body.goto(700, ycor)
self.body.showturtle()
self.body.goto(-700, ycor)
I can't figure it out to solve this bug. I'm using Turtle module.
The two car objects are created, but the problem is that you haven't implemented real-time movement for multiple turtles, so the first turtle completes its 5-second journey across the screen before the second one is created or begins moving.
When you encounter problems like this, my suggestion is to strip the problem down to a minimal, reproducible example. This process makes the problem obvious by removing the noise. For example, if you move the spawn and destination points onto the visible screen, the problem becomes clear.
Here's an even more minimal demonstration:
from turtle import Turtle
t = Turtle()
tt = Turtle()
t.speed(2)
tt.speed(2)
t.goto(100, 100)
tt.goto(200, 100)
t.Screen().exitonclick()
When you run this, you'll see that t moves from 0, 0 to 100, 100 in about a second. Only once t arrives at the destination does tt even begin moving. Adding print statements on each line is another way to see that each goto blocks the script completely until the slow movement completes. The simultaneous movement you expect is not the default behavior of turtle.
The typical solution is to use tracer(0) to disable the internal update/rendering loop that turtle uses to smooth out gotos. Once you've done this, you can reposition turtles at will and call turtle.update() to render a frame. It's up to you to reimplement smooth movement, which is not difficult to do.
Also worth noting, your exitonclick call is never reached and the for loop with if n == 59: is pointless. Cars are never garbage collected, and probably shouldn't be doing so much work in the initializer. Kudos for using composition rather than inheritance for your classes, though.
I'd also caution against adding complexity like multiple classes and files before you've convinced yourself that the basics are operational. If something as simple as movement isn't working as you expect, all of that other stuff only gets in the way of debugging. Run your code often, building up guarantees about its behavior as you work.
Here's a quick sketch of how you might begin to redesign your project. It's based on my recommended real-time setup for turtle.
import turtle
class Car:
def __init__(self, x, y, speed):
self.x = x
self.y = y
self.speed = speed
self.body = turtle.Turtle()
self.body.shape("square")
self.body.penup()
self.body.goto(x, y)
def move(self):
self.x -= self.speed
w = turtle.screensize()[0]
if self.x < -w:
self.x = w
self.body.goto(self.x, self.y)
def tick():
for action in keys_pressed:
actions[action]()
for car in cars:
car.move()
turtle.update()
win.ontimer(tick, frame_delay_ms)
if __name__ == "__main__":
w, h = turtle.screensize()
turtle.tracer(0)
t = turtle.Turtle()
t.penup()
t.goto(0, -h + 50)
t.left(90)
cars = [
Car(w, -200, 3),
Car(w, -100, 5),
Car(w, 0, 4.5),
Car(w, 100, 4),
Car(w, 200, 6),
]
frame_delay_ms = 1000 // 30
step_speed = 10
actions = dict(
u=lambda: t.forward(step_speed),
)
win = turtle.Screen()
keys_pressed = set()
win.onkeypress(lambda: keys_pressed.add("u"), "Up")
win.onkeyrelease(lambda: keys_pressed.remove("u"), "Up")
win.listen()
tick()
win.exitonclick()

Turtle not displaying on screen - Python

I am trying to recreate the snake game, however when I call the function which is supposed to create the initial body of the snake nothing appears on the screen.
The same problem happens if I simply create a turtle object in the main file.
Snake:
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
def create_snake (self):
for position in STARTING_POSITIONS:
n_segment = Turtle("square")
n_segment.color("white")
n_segment.penup()
print(position)
n_segment.goto(position)
self.segments.append(n_segment)
Main:
from turtle import Turtle, Screen
from snake import Snake
screen = Screen()
screen.setup(width = 600 , height= 600)
screen.bgcolor("black")
screen.title("SNAKE")
screen.tracer(0)
game_on = True
segments = []
snake = Snake()
turtle = Turtle()
In order to see the snake, I just added the following code snippet in main.py after the turtle definition to display a stationary snake with a pointer.
while game_on:
screen.update()
screen.exitonclick()
The result was this image.
Hope that helps.
Regards.
this is a minimum reproducible example of the above code which works and draws a square (segment of the snake body) in the snake class:
import turtle as ttl
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
def create_snake (self):
ttl.shape('square')
ttl.color('white')
screen = ttl.Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
snake = Snake()
ttl.done()
A lot of the code from the OP question is removed because there were numerous errors. Also, for the purpose of simplicity the class was added to the code, but the OP could break it into two separate files if desired.
I believe that there error in the question code was that the screen was drawing over itself which is why it was always black.
You can build from here.

Python turtle object wont show in window

I am currently trying to make a copy of Atari's breakout using python and turtle. Previously I have created a pong copy which does not use OOP and it worked perfectly fine. However due to the bricks in breakout I decided to use OOP and create an object class for the bricks. Once I run the program, it wont display the brick. Any ideas to why?
import turtle
window = turtle.Screen()
window.title('Atari Breakout')
window.bgcolor('black')
window.setup(width=800, height=600)
window.tracer(0)
class Brick(Turtle):
def __init__(self):
super().__init__(shape='square', visible=True)
self.myturtle = turtle.Turtle()
self.color = 'white'
self.shapesize(stretch_wid=10, stretch_len=4)
self.pendown()
self.goto(-350, 200)
board1 = Brick()
window.update()
There are a few problems in this code - firstly, you need turtle.Turtle not just Turtle as otherwise this causes an error. Secondly, the line self.myturtle = turtle.Turtle() is unnecessary as super().__init__(shape='square', visible=True) already creates a turtle, and thirdly self.color = 'white' should be changed to self.color('white'). Also, I'm pretty sure you meant self.penup() not self.pendown() to stop the brick from drawing a line from the center to its position.
Completed code:
import turtle
window = turtle.Screen()
window.title('Atari Breakout')
window.bgcolor('black')
window.setup(width=800, height=600)
window.tracer(0)
class Brick(turtle.Turtle):
def __init__(self):
super().__init__(shape='square', visible=True)
self.color('white')
self.shapesize(stretch_wid=10, stretch_len=4)
self.penup()
self.goto(-350, 200)
board1 = Brick()
window.update()

Why does my turtle object give an error with the setx(x) function?

I'm making a space invaders game, trying to get more comfortable with Python. So I started with the player movement. In my main class I first create the player. After that I try to call the movement methods. But for some reason it looks like I can't call any turtle statements with the player object. Why has it lost it's turtle attribute?
It's for my space invader game. I tried multiple statements from the turtle library. But none of them seem to work. I tried goto, setx(x), setposition.
import turtle
class Player:
movementSpeed = 0
xcor = 0
ycor = 0
def __init__(self, movementSpeed, xcor, ycor):
self.movementSpeed = movementSpeed
self.xcor = xcor
self.ycor = ycor
self = turtle.Turtle()
self.color("blue")
self.shape("triangle")
self.penup()
self.speed(0)
self.setposition(xcor, ycor)
self.setheading(90)
def move_left(self):
x = self.xcor
x -= self.movementSpeed
if x < -280:
x = -280
self.setx(x)
def move_right(self):
x = self.xcor
x += self.movementSpeed
if x > 280:
x = 280
self.turtle.setx(x)
from Player import Player
player = Player(movementSpeed, 0 ,-250)
wn.onkey(speler.move_left, "Left")
wn.onkey(speler.move_right, "Right")
I expected that the player object to move.
But the following error showed up
AttributeError: 'Player' object has no attribute 'turtle'
Basic solution
In the __init__ you assign turtle object to self instead of assigning to self.turtle so there's no surprise it does not have such attribute.
If you want it to have it, change the mentioned line in the constructor to:
self.turtle = turtle.Turtle()
More detailed solution
You are mixing two different approaches: Player being a Turtle and Player consisting of a Turtle. If you want the first one, use inheritance:
class Player(turtle.Turtle):
def __init__(self, *args, **kwargs):
super(Player, self).__init__(*args, **kwargs)
# the rest of the initialization
and then use all methods and attributes of Turtle as their are Player's, like:
self.shape("triangle")
In the case of Player consisting of/containg a Turtle just use basic solution and in the constructor setup Player's turtle properly:
self.turtle = turtle.Turtle()
self.turtle.color("blue")
self.turtle.shape("triangle")
self.turtle.penup()

Categories