首页 > 解决方案 > Python,函数没有被随机调用

问题描述

我已经完成了石头剪刀布或纸质程序的编写。我有一个函数 ai() 可以随机决定计算机端。此函数还打印每次循环完成时我调用的计算机的决定,但是,有时它只是不这样做。你能帮我弄清楚为什么吗?任何改进建议都非常受欢迎

这是我的功能

def ai():
    number = random.randint(1,4)
    if number == 1:
        global aiinput
        aiinput = ("rock")
        print(("The choice of computer is: "),aiinput)
    elif number == 2:
        aiinput = ("paper")
        print(("The choice of computer is: "),aiinput)
    elif number == 3:
        aiinput = ("scissors")
        print(("The choice of computer is: "),aiinput)

这是我剩下的代码


import random

def ai():
    number = random.randint(1,4)
    if number == 1:
        global aiinput
        aiinput = ("rock")
        print(("The choice of computer is: "),aiinput)
    elif number == 2:
        aiinput = ("paper")
        print(("The choice of computer is: "),aiinput)
    elif number == 3:
        aiinput = ("scissors")
        print(("The choice of computer is: "),aiinput)

def draw():
    print ("Draw")
def loser():
    print ("Loser!")
def winner():
    print ("You won!")

print("Welcome to the game to quit prompt q")
while True:
    usrinp = input("rock, scissors or paper? you can also prompt r,s or p: ")
    ai()
    if usrinp == ("r") and aiinput == ("rock"):
        draw()
    elif usrinp == ("r") and aiinput == ("paper"):
        loser()
    elif usrinp == ("r") and aiinput == ("scissors"):
            winner()


    if usrinp == ("p") and aiinput == ("rock"):
        winner()
    elif usrinp == ("p") and aiinput == ("paper"):
        draw()
    elif usrinp == ("p") and aiinput == ("scissors"):
        loser()

    if usrinp == ("s") and aiinput == ("rock"):
        loser()
    elif usrinp == ("s") and aiinput == ("paper"):
        winner()
    elif usrinp == ("s") and aiinput == ("scissors"):
        draw()
    if usrinp == ("q"):
        quit()

在这里你可以看到调试 调试结果

标签: python

解决方案


您只需在函数中设置global aiinputa 。在ifs之前做。您还需要使用.ifairandint(1, 3)

def ai():
    global aiinput # This goes before the conditions.      
    aiinput = {1: "rock",
               2: "paper",
               3: "scissors"}[random.randint(1, 3)]
    print("The choice of computer is: ", aiinput)

推荐阅读