Python嵌套条件吗?双重条件后跟另一个条件

问题描述 投票:0回答:1

我正在尝试学习python,但在这个问题上苦苦挣扎。

想象这种情况:

1-用户按下button1和button2 =程序需要“做一些”

2-用户按下button1和button2然后按下button3 =我可以“做一些2”]

3-用户按下button2和button1然后按下button3 =我可以“做一些2”]

但是

4-如果用户在button1和button2之前按下button3 =对我来说“做某事”不是可以的,我只需要“做某事”

所以首先按下哪个按钮的顺序对我来说很重要

def button1_pressed():  # Returns true if the left mouse button is pressed
    button1_state = win32api.GetKeyState(0x01)
    return button1_state < 0

def button2_pressed():  # Returns true if the right mouse button is pressed
    button2_state = win32api.GetKeyState(0x02)
    return  button2_state < 0

def button3_pressed():  # Returns true if the M button is pressed
    button3_state = win32api.GetKeyState(0x4D)
    return button3_state < 0

while True:
    while button1_pressed() and button2_pressed(): # No matter which one is pressed first to me
        print("do some")
        while button3_pressed(): # Only if it is pressed after button1 and button2 are pressed
            print("do some2")
            if button2_pressed() == 0:
                break # this only breaks the inner while loop
        break # added an extra break else it would just be stuck in an endless loop

如果有人帮助我,我将非常感激。

python python-3.x nested-loops
1个回答
0
投票

这里您想要的是所谓的“状态机”。您描述的情况称为“状态”,它们在按钮按下停止后仍然存在(例如,您可能处于“用户按下按钮2”的状态,这与“用户按下按钮2”的状态不同)。

pressed = [True, False, False, False]
while True:
  if button1_pressed() and not pressed[1]:
      pressed[1] = True
      if pressed[2]:
          print("do some")
          continue
  if button2_pressed() and not pressed[2]:
      pressed[2] = True
      if pressed[1]:
          print("do some")
          continue
  if button3_pressed() and not pressed[3]:
      pressed[3] = True
      if pressed[1] and pressed[2]:
          print("do some 2")
  if all(pressed):
      # All the buttons have been pressed (in some order).  Done!
      break

您可能将其编码为数据结构,如下所示:

buttons = [lambda: False, button1_pressed, button2_pressed, button3_pressed]
pressed = [True, False, False, False]
actions = {
    # For each button press, what action happens 
    # based on button(s) previously pressed.
    1: ([2], "do some")
    2: ([1], "do some")
    3: ([1, 2], "do some 2")
}
while True:
    for num in (1, 2, 3):
        if not buttons[num]() or pressed[num]:
            continue
        pressed[num] = True
        prev, action = actions[num]
        if all(pressed[p] for p in prev):
            print(action)
    if all(pressed):
        break
© www.soinside.com 2019 - 2024. All rights reserved.