0

So I followed the instructions here on how to take two inputs at the same time to execute a different function than either key press individually.

My code doesn't want to work but only the function that requires two key presses ('w', 'a'): upLeft and I can't figure out why. I tested my function in the provided solution and it worked. I can't seem to see any tangible differences between what I have here and what is provided in the link.

import turtle
import time


# Draw initial screen
wn = turtle.Screen()
wn.title("Cool Game Bro")
wn.bgcolor("grey")
wn.setup(width=800, height=600)
wn.tracer(0)


# main player character
character = turtle.Turtle()
character.speed(0)
character.shape("circle")
character.color("yellow")
character.penup()
character.goto(0, 0)

def process_events():
    events = tuple(sorted(key_events))

    if events and events in key_event_handlers:
        (key_event_handlers[events])()

    key_events.clear()

    wn.ontimer(process_events, 200)

def Up():
    key_events.add('w')
def Left():
    key_events.add('a')
def Down():
    key_events.add('s')
def Right():
    key_events.add('d')

def charUp():
    y = character.ycor()
    y += 10
    character.sety(y)

def charLeft():
    x = character.xcor()
    x -= 10
    character.setx(x)

def charRight():
    x = character.xcor()
    x += 10
    character.setx(x)

def charDown():
    y = character.ycor()
    y -= 10
    character.sety(y)

def upLeft():
    y = character.ycor()
    y+=10
    character.sety(y)
    x = character.xcor()
    x -=10
    character.setx(x)


key_event_handlers = { \
    ('w',): charUp,\
    ('a',): charLeft,\
    ('d',): charRight,\
    ('s',): charDown,\
    ('w', 'a'): upLeft,\
}

key_events = set()

wn.onkeypress(Up, 'w')
wn.onkeypress(Left, 'a')
wn.onkeypress(Right, 'd')
wn.onkeypress(Down, 's')

wn.listen()
process_events()

while True:
    wn.update()

Appreciate the help!

Multiplify
  • 31
  • 5

1 Answers1

1

A set stores things alphabetically. Use

   ('a','w'): upLeft

and it will work fine.

BTW1, you could have learned this if you had just added print(events) in your process_events function, as I did.

BTW2, you don't need backslashes in your definition. Anything contained in parens, square brackets, or curly brackets can automatically be continued onto another line.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30