简体   繁体   中英

Multiple key presses for a single action python 3.6

Im currently attempting to make a game using only python and its built in plugins, not pygame. I was wondering if it is possible to push two keys to make the character move diagonally. This is my current movement code, I know it looks bad, I'm still obviously a beginner.

#movement functions and stuff
def go_up():
    char.direction = "up"

def go_down():
    char.direction = "down"

def go_left():
    char.direction = "left"

def go_right():
    char.direction = "right"

def go_up_left():
    char.direction = "up_left"

def move():

    if char.direction == "up":
        y = char.ycor()
        char.sety(y + speed)


    if char.direction == "down":
        y = char.ycor()
        char.sety(y - speed)


    if char.direction == "left":
        x = char.xcor()
        char.setx(x - speed)


    if char.direction == "right":
        x = char.xcor()
        char.setx(x + speed)

    if char.direction == "up_left":
        x = char.xcor()
        y = char.ycor()
        char.setx(x - speed)
        char.sety(y + speed)

# key bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
wn.onkeypress(go_up_left, "")

As you can see, I dont have the key bindings for "go_up_left" because that's what I need help with.

use pygame lib and like this code shows how to handle multiple key pressing through pygame.key.get_pressed()

keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and keys[pygame.K_RIGHT]:
    movementx+y+() #example to move up and right at the same time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM