BRADLEY LARSEN
BRADLEY LARSEN

Reputation: 11

If loop help needed

I am in a High school coding class and I'm trying to use a def to move a turtle up 20 pixels. I have this working but I am having trouble on one part.

I need to use an if statement to see if they pressed a certain button "3,2,1" and if they don't then it resets them to a starting position

import turtle as trtl
rocketship_image = "rocketship.gif"

up = -50

wn = trtl.Screen()
wn.setup(width=1.0, height=1.0)
wn.addshape(rocketship_image)
wn.bgpic("Screenshot 2020-11-18 at 8.47.14 PM.png")

rocketship = trtl.Turtle()

def start_pos():
  rocketship.pu()
  rocketship.goto(0,-250)

rocketship.right(90)
start_pos()

def draw_rocketship(active_rocketship):
active_rocketship.pu()
active_rocketship.shape(rocketship_image)

def drop_rocketship():
  global up
  rocketship.pu()
  rocketship.clear()
  rocketship.forward(up)
  draw_rocketship(rocketship)


draw_rocketship(rocketship)

if wn.onkeypress(drop_rocketship, "3"):
  drop_rocketship()

The if statement is incomplete because I'm stuck on that part. Also, is there any way for it to reset if the input is not "3,2,1"?

Incidentally, the wn.bgpic is a space image.

Upvotes: 1

Views: 72

Answers (1)

chenjesu
chenjesu

Reputation: 754

If you're pressing "3", then "2", then "1", in a sequence, you will probably want something like this:

...
sequence_321 = 0
if wn.onkeypress(drop_rocketship, <any other key>):
  sequence_321 = 0
if wn.onkeypress(drop_rocketship, "3"):
  sequence_321 = 3
if wn.onkeypress(drop_rocketship, "2") and sequence_321 == 3:
  sequence_321 = 2
if wn.onkeypress(drop_rocketship, "1") and sequence_321 == 2:
  <reset to starting position>

This should make it so that when you press "3", let go, press "2", let go, then press "1", it will call whatever the reset function is. It will also work after you press "3", then "2", then "1", without any of those keys being let go of. If you're trying to only do this after 3, 2, and 1 are held down in succession, with all three being held down at the end, the logic will be different. The above code should work for both "3,2,1" being held down at all once and also being pressed one at a time.

Upvotes: 2

Related Questions