代码之家  ›  专栏  ›  技术社区  ›  Adrian DSouza

python中逻辑语句的组合(and、or)

  •  1
  • Adrian DSouza  · 技术社区  · 7 年前

    我目前正在tkinter制作一个石头、布、剪刀射击游戏,并试图编写一个函数来决定谁获胜。1=石头,2=布,3=剪刀。脚本不会打印任何内容,除非comp==2且choice==1。

    def Winning():
        if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or
            ((comp == 1) and (choice == 3))):
            messagebox.showinfo("Info", "YOU LOSE!!!")
        if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2)) 
          or ((choice == 1) and (comp == 3))):
            messagebox.showinfo("Info", "YOU WIN!!!")
        else:
            messagebox.showinfo("Info", "DRAW!!!")
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   cdlane    7 年前

    我认为你走错了方向。假设我们必须使用数字输入,我会:

    ROCK, PAPER, SCISSORS = range(1, 4)
    
    roshambo = {
        ROCK: SCISSORS,
        PAPER: ROCK,
        SCISSORS: PAPER
    }
    
    def Winning(comp, choice):
        if comp == choice:
            messagebox.showinfo("Info", "DRAW!!!")
        elif comp == roshambo[choice]:
            messagebox.showinfo("Info", "YOU WIN!!!")
        else:
            messagebox.showinfo("Info", "YOU LOSE!!!")
    

    这使您的逻辑清晰,并简化了代码。而且,它更容易扩展问题:

    ROCK, PAPER, SCISSORS, LIZARD, SPOCK = range(1, 6)
    
    roshambo = {
        ROCK: [LIZARD, SCISSORS],
        PAPER: [ROCK, SPOCK],
        SCISSORS: [PAPER, LIZARD],
        LIZARD: [SPOCK, PAPER],
        SPOCK: [SCISSORS, ROCK]
    }
    
    def Winning(comp, choice):
        if comp == choice:
            messagebox.showinfo("Info", "DRAW!!!")
        elif comp in roshambo[choice]:
            messagebox.showinfo("Info", "YOU WIN!!!")
        else:
            messagebox.showinfo("Info", "YOU LOSE!!!")
    

    字典是你的朋友,没有字典就不要编程!

        2
  •  0
  •   Paul    7 年前

    您的函数从何处获取 comp choice ?

    像这样的方法会奏效:

    from tkinter import messagebox
    
    rock=1
    paper=2
    scissors=3
    
    
    def Winning(comp, choice):
        if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or((comp == 1) and (choice == 3))):
            messagebox.showinfo("Info", "YOU LOSE!!!")
        if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2)) or((choice == 1) and (comp == 3))):
            messagebox.showinfo("Info", "YOU WIN!!!")
        else:
            messagebox.showinfo("Info", "DRAW!!!")
    
    
    Winning(rock, paper)
    

    这就是你想要的吗?