So, i was making a pac-man game, i was setting up the keybinds to make the character move. When i hit the "Up"
button, The Character moves right instead of moving up.
I used this code to move the pac-man character:
import turtle
# draw a window with turtle for the pac-man game
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Pac-Man")
wn.setup(width=800, height=600)
wn.tracer(0)
# create a turtle for the pac-man
pacman = turtle.Turtle()
pacman.speed(0)
pacman.shape("circle")
pacman.color("white")
pacman.penup()
# create the keybinds for the pacman WASD using a def
def w():
pacman.forward(20)
def a():
pacman.left(90)
def s():
pacman.forward(-20)
def d():
pacman.right(90)
# loop
wn.listen()
wn.onkey(w, "Up")
wn.onkey(a, "Left")
wn.onkey(s, "Down")
wn.onkey(d, "Right")
# while true window loop
while True:
wn.update()
if pacman.xcor() > 280 or pacman.xcor() < -280:
pacman.right(180)
if pacman.ycor() > 280:
pacman.left(180)
Also, I would like to know if the code above is complete.
From turtle, I see that "forward" is not mean to go left,right or any other axis, it only move toward the direction the turtle is facing at the present time. In your case I don't think this is the right way to do it, even for the "d" key per example, you turtle will turn 90 degrees clockwise each time you press "d" key.
In the beginning, the turtle is facing east when it's created, you can use setheading() :
# Up
def w():
pacman.setheading(0) # north
pacman.forward(20)
# Down
def w():
pacman.setheading(180) # south
pacman.forward(20)
# Left
def w():
pacman.setheading(270) # west
pacman.forward(20)
# Right
def w():
pacman.setheading(90) # east
pacman.forward(20)
Please check the website, depending on your mode, the degrees can change. Hope it help.