Home > Mobile >  How do you use dx?
How do you use dx?

Time:02-24

I have a slight issue with my code:

import turtle

wn = turtle.Screen()
wn.bgcolor('lightblue')

cup = turtle.Turtle()
cup.shape('square')
cup.shapesize(1.5, 1)
cup.speed(0)
cup.dy = 1
cup.dx = 2
cup.penup()

gravity = 0.1


def face_right():
    cup.setheading(310)


def face_left():
    cup.setheading(45)


def jump_right():
    cup.dy *= -1


def jump_left():
    cup.dx *= -1
    cup.dy  = gravity


def do_right():
    jump_right()
    face_right()


def do_left():
    face_left()
    jump_left()


wn.listen()

wn.onkeypress(do_right, 'Right')
wn.onkeypress(do_left, 'Left')


wn.listen()

while True:
    wn.update()
    cup.dy -= gravity
    cup.sety(cup.ycor()   cup.dy)

    cup.setx(cup.xcor()   cup.dx)

As you can see, when you run the code the "jump right" function works just fine. The jump left one? not so much. I have tried solving this by trying tons of different possible combinations but none seem to work. All I want in the game is the jump right function but instead, it jumps left when the left arrow key is pressed. I was given a challenge to make a full game with only turtle but I don't know if i'll be able to continue anymore.

Thanks so much in advance!

PS I'm using python 3

CodePudding user response:

dx and dy are the amount of change in position. If dx is 2, it means to move right 2 repeatedly for a certain amount of time. Also, dy is the amount of change in the up and down position. You implement it by adding or subtracting, not multiplying the amount of change. Multiplying will change the amount of change in position very abruptly, multiplying by a negative number means changing direction. Below is the modified code for your code.

import turtle

wn = turtle.Screen()
wn.bgcolor('lightblue')

cup = turtle.Turtle()
cup.shape('square')
cup.shapesize(1.5, 1)
cup.speed(0)
cup.dy = 1
cup.dx = 2
cup.penup()

gravity = 0.1


def face_right():
    cup.setheading(310)


def face_left():
    cup.setheading(45)


def jump_right():
    cup.dx  = 3
    cup.dy  = 3


def jump_left():
    cup.dx  = -3
    cup.dy  = 3


def do_right():
    jump_right()
    face_right()


def do_left():
    face_left()
    jump_left()

wn.onkeypress(do_right, 'Right')
wn.onkeypress(do_left, 'Left')

wn.listen()

while True:
    wn.update()
    cup.dy -= gravity
    cup.sety(cup.ycor()   cup.dy)
    cup.setx(cup.xcor()   cup.dx)

Or if you want a faster moving and jumping,

def jump_right():
    cup.dx = 3
    cup.dy = 3


def jump_left():
    cup.dx = -3
    cup.dy = 3
  • Related