How to move object around with arrow keys in python turtle - python

I am trying to move the object around the screen with the arrow keys. I have left and right how I want them, but when I am trying to go up it doesn't work how I want.
I tried to use player.left(90) then move forward but then I have to use the right arrow key to move up. I would prefer to not even have the object rotate 90deg
I just want to easily move the object around the window.
python
import turtle
window = turtle.Screen()
window.bgcolor('black')
player = turtle.Turtle()
player.shape('square')
player.color('white')
player.penup()
def move_left():
player.color('light green')
player.backward(10)
def move_right():
player.color('light green')
player.forward(10)
def move_up():
player.color('light green')
player.left(90)
player.forward(10)
window.onkeypress(move_left, "Left")
window.onkeypress(move_right, "Right")
window.onkeypress(move_up, "Up")
window.listen()
turtle.done()

Related

Why won't my square move right? I'm trying all different methods to move it in turtle module it works for up and down but not left and right?

# Game creation
import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("Black")
wn.setup(width=800, height=800)
wn.tracer(0)
# paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.penup()
paddle_a.goto(0, 0)
# Functions
def paddle_a_right():
turtle.forward(100)
wn.onkeypress(paddle_a_right, 'd')
while True:
wn.update()
Want the square to move to the right or left using 'a' or 'd' I don't know very much about turtle, I just want to program a simple game.
There are three major issues with your code. First, you need to call wn.listen() to allow the window to receive keyboard input. Second, you do turtle.forward(100) when you mean paddle_a.forward(100). Finally, since you did tracer(0), you now need to call wn.update() anytime a change is made that you want your user to see.
Here's a simplified example:
from turtle import Screen, Turtle
def paddle_right():
paddle.forward(10)
screen.update()
screen = Screen()
screen.title("Pong")
screen.bgcolor("Black")
screen.setup(width=800, height=800)
screen.tracer(0)
paddle = Turtle()
paddle.shape("square")
paddle.color("white")
paddle.penup()
screen.onkeypress(paddle_right, 'd')
screen.listen()
screen.update()
screen.mainloop()

Python turtle not moving on arrow press

I am trying to make my turtle (main_ship) move across the bottom of my screen according to when the user presses the left and right arrow keys but the turtle is not moving. I have used the same code before when making Pong so I'm not sure why it's not working.
import turtle
wn = turtle.Screen()
wn.title("Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
main_ship = turtle.Turtle()
main_ship.speed(0)
main_ship.shape("turtle")
main_ship.color("green")
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.penup()
main_ship.goto(0, -290)
main_ship.left(90)
def main_ship_right():
x = main_ship.xcor()
x += 20
main_ship.setx(x)
def main_ship_left():
x = main_ship.xcor()
x -= 20
main_ship.setx(x)
while True:
wn.update()
wn.mainloop()
wn.listen()
wn.onkeypress(main_ship_right, "Right")
wn.onkeypress(main_ship_left, "Left")
When I press the arrow keys, nothing happens but the code still runs and there are no error messages.
You have to assign keys before mainloop() which runs all time till you close window.
You don't need while True because mainloop() already runs internal loop.
You may have to remove wm.tracer(0) or you will have to run wn.update() to refresh elements in window.
import turtle
# --- functions ---
def main_ship_right():
x = main_ship.xcor()
x += 20
main_ship.setx(x)
wn.update()
def main_ship_left():
x = main_ship.xcor()
x -= 20
main_ship.setx(x)
wn.update()
# --- main ---
wn = turtle.Screen()
wn.title("Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
main_ship = turtle.Turtle()
main_ship.speed(0)
main_ship.shape("turtle")
main_ship.color("green")
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.penup()
main_ship.goto(0, -290)
main_ship.left(90)
wn.update()
wn.listen()
wn.onkeypress(main_ship_right, "Right")
wn.onkeypress(main_ship_left, "Left")
wn.mainloop()
For this style of motion, there's another way to implement it. The idea is to leave the cursor moving in it's original orientation, but use settiltangle() to make it look like it's facing upward.
This lets us use forward(20) and backward(20) to move our cursor, and not have to write:
x = main_ship.xcor()
x += 20
main_ship.setx(x)
Works great for Space Invader style games, where the player faces upwards but moves sideways:
from turtle import Screen, Turtle
from functools import partial
screen = Screen()
screen.title("Game")
screen.bgcolor('black')
screen.setup(width=800, height=600)
main_ship = Turtle('turtle')
main_ship.speed('fastest')
main_ship.color('green')
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.settiltangle(90)
main_ship.penup()
main_ship.sety(-290)
screen.onkeypress(partial(main_ship.forward, 20), 'Right')
screen.onkeypress(partial(main_ship.backward, 20), 'Left')
screen.listen()
screen.mainloop()
Only works in the turtle library that comes with Python -- online Python development sites usually provide limited turtle implementations that don't include methods like settiltangle().

My Python turtle window crashes when using onkey event

My Python turtle window crashes when I try to move to the left. I am using the onkey in Python turtle graphics and when I try to use it my window completely crashes. Here is my code:
import turtle
wn = turtle.Screen()
wn.bgcolor("green")
crosshair = turtle.Turtle()
crosshair.shape("circle")
draw = turtle.Pen()
draw.color("brown")
draw.ht()
while True:
def left():
draw.st()
draw.penup()
draw.left(90)
draw.forward(50)
draw.pendown()
draw.forward(100)
draw.left(90)
draw.forward(50)
draw.right(90)
draw.forward(100)
draw.right(90)
draw.forward(100)
draw.right(90)
draw.forward(100)
draw.right(90)
draw.forward(50)
turtle.listen()
turtle.onkey(left, "Left")
Your code isn't structured properly. You should not have an infinite while True: loop when using turtle. Instead, you should set up your event handlers, like onkey(), and turn control over to Tk's event loop using mainloop(). Python-wise, you don't need to define left() inside the loop, move it to the top level. Here's a rework that includes the above changes:
from turtle import Turtle, Screen
def left():
draw.st()
draw.penup()
draw.left(90)
draw.forward(50)
draw.pendown()
draw.forward(100)
draw.left(90)
draw.forward(50)
draw.right(90)
for _ in range(3):
draw.forward(100)
draw.right(90)
draw.forward(50)
draw.ht()
screen = Screen()
screen.bgcolor("green")
crosshair = Turtle("circle")
draw = Turtle(visible=False)
draw.color("brown")
screen.onkey(left, "Left")
screen.listen()
screen.mainloop()
Click on the window to make it active, then you can use your left arrow key to invoke the graphics:

making an endpoint in turtle graphics

I'm making a maze with turtle graphics for a class project and I have one more main thing to complete before I'm finished...
I've created a second "turtle" to make a box at the endpoint. So the objective is to finish the maze and get the turtle in the box. But I am unsure how to make the box an actual endpoint and have a message pop up.
Here is my code:
from turtle import Turtle, Screen
screen = Screen()
screen.setup(650, 850)
screen.title("Turtle Keys")
screen.bgpic('scooby_doo_maze.gif')
move = Turtle(shape="triangle")
move.penup()
move.setx(-150)
move.sety(200)
move.pendown()
move.pensize(5)
box = Turtle(shape="square")
box.hideturtle()
box.speed(0)
box.penup()
box.setx(150)
box.sety(-190)
box.pendown()
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
def keyUp():
move.forward(12)
def keyLeft():
move.left(90)
def keyRight():
move.right(90)
def keyDown():
move.backward(12)
def keyReset():
move.reset()
move.penup()
move.setx(-150)
move.sety(200)
move.pendown()
move.pensize(5)
screen.onkey(keyUp, "Up")
screen.onkey(keyLeft, "Left")
screen.onkey(keyRight, "Right")
screen.onkey(keyDown, "Down")
screen.onkey(keyReset, "r")
screen.listen()
screen.exitonclick()
We just need to add few features. First, instead of drawing the end point with turtle box, we make turtle box the endpoint by expanding the turtle itself via box.shapesize(). This way, we can use move.distance(box) to determine if move is near the center of box.
Second, we need a function called by all the movement functions to test if above distance is close enough and then invoke the following:
Third, we introduce screen.textinput() to let the play know they've succeeded and offer then the option to play again, or quit. I've reworked your code below to introduce these additions and tweak it a bit for style:
from turtle import Turtle, Screen
screen = Screen()
screen.setup(650, 850)
screen.title("Turtle Keys")
screen.bgpic('scooby_doo_maze.gif')
def insideBox():
if move.distance(box) < 60:
play_again = screen.textinput("Success!", "Play again?")
if play_again and play_again.lower().startswith('y'):
keyReset()
else:
screen.bye()
def keyUp():
move.forward(12)
insideBox()
def keyLeft():
move.left(90)
def keyRight():
move.right(90)
def keyDown():
move.backward(12)
insideBox()
def keyReset():
move.reset()
move.penup()
move.goto(-150, 200)
move.pendown()
move.pensize(5)
screen.listen() # it's here because screen.textinput() unsets it
screen.onkey(keyUp, "Up")
screen.onkey(keyLeft, "Left")
screen.onkey(keyRight, "Right")
screen.onkey(keyDown, "Down")
screen.onkey(keyReset, "r")
move = Turtle(shape="triangle")
keyReset()
box = Turtle(shape="square")
box.color("black", "white")
box.shapesize(5, 5, 5)
box.penup()
box.goto(150, -190)
screen.mainloop()
This is a situation where I would avoid screen.exitonclick() as you need to click the window to get it to listen and easily end up closing it! Using screen.mainloop() should be sufficient and let the user close the window by not choosing to play again or using the window controls.

Creating a turtle program that does commands based upon the button pressed

I haven't been able to find anything online for this but I need to create a program that:
If the left button is pressed, the turtle should move to that location and draw a small square.
If the right button is pressed, the turtle should move that that location and draw a small circle.
If the middle button is pressed, the turtle should change to a different random color.
You should also change the color if the use presses the space bar.
Any suggestions on how to start?
Here is some code I have tried so far:
def k2(x,y): turtle.penup() turtle.setposition(x,y) turtle.pendown() turtle.circle(radius)
This is the top from turtle
import * setup(500, 500) Screen() title("Turtle Keys") move = Turtle() showturtle()
This is the bottom
onkey(k1, "Up") onkey(k2, "Left") onkey(k3, "Right") onkey(k4, "Down") listen() mainloop()
Below is my guess as to what you and your code snippets describe. Note that I changed the circle and square functions from the left and right keyboard buttons to the left and right mouse buttons which seemed to make more sense in the context of, "move to that location":
import turtle
import random
colors = ["red", "orange", "yellow", "green", "blue", "violet"]
radius = 10
width = 20
LEFT, MIDDLE, RIGHT = 1, 2, 3
def k1(x=None, y=None): # dummy arguments so can be a click or key
turtle.color(random.choice(colors))
def k2(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
for _ in range(4):
turtle.forward(width)
turtle.right(90)
def k3(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
turtle.circle(radius)
turtle.setup(500, 500)
turtle.Screen().title("Turtle Keys")
turtle.onkey(k1, " ")
turtle.onscreenclick(k2, btn=LEFT)
turtle.onscreenclick(k1, btn=MIDDLE)
turtle.onscreenclick(k3, btn=RIGHT)
turtle.listen()
turtle.mainloop()

Categories