Функция не вызывается во время цикла - PullRequest
0 голосов
/ 29 апреля 2020

Я создал функцию loss (), win () и draw (), чтобы изменить счет после событий. Проблема в том, что их не вызывают в то время, как l oop меняет счет и устанавливает его правильно , У меня были строки для каждого оператора if и elif, но я решил использовать функцию, чтобы сделать код короче и эффективнее.

    from random import randint
    print("Welcome to this game of rock paper scissors against the computer.")
    print("Good luck and have fun! Enjoy this game! ")
    print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")
    scoreH=0
    scoreAI=0
    Round=0

   def loss():
        scoreH=scoreH+0
        scoreAI=scoreAI+1
    def win():
        scoreH=scoreH+1
        scoreAI=scoreAI+0
    def draw():
        scoreH=scoreH+0
        scoreAI=scoreAi+0        

    x=True


    while x == True :
        # Choice
        Round=Round+1
        print("Round",Round,"is going to start. ")
        print("1.Rock")
        print("2.Paper")
        print("3.Scissors")
        choice=input("Enter your choice: ").lower()
        IntChoice=randint(1,3)


        #Transforming AI_choice from an int to a string 
        if IntChoice == 1:
            AI_choice="rock"
        elif IntChoice == 2:
            AI_choice="paper"
        elif IntChoice == 3:
            AI_choice="scissors"

        print(AI_choice)

        # Draw
        if choice==AI_choice:
            draw()
            print("The computer chose",choice,".You draw.")
        # PlayerWins
        elif choice=="paper" and AI_choice=="rock":
            win()
            print("The computer chose",choice,".You win.")
        elif choice=="scissors" and AI_choice=="paper":
            win()
            print("The computer chose",AI_choice,".You win.")
        elif choice=="rock" and AI_choice=="scissors":
            win()
            print("The computer chose",AI_choice,".You win.")
        # AIwins
        elif AI_choice=="paper" and choice=="rock":
            loss()
            print("The computer chose",AI_choice,".You lose.")
        elif AI_choice=="scissors" and choice=="paper":
            loss()
            print("The computer chose",AI_choice,".You lose.")
        elif AI_choice=="rock" and choice=="scissors":
            loss()
            print("The computer chose",AI_choice,".You lose.")
        else:
            print("Invalid input.")
            continue
        end=input()
        # Stop Playing
        if end == "stop" or end == "quit":
            print("The score is :",scoreH,"-",scoreAI)
            if scoreH > scoreAI:
                print("You win.")
            elif scoreH < scoreAI:
                print("You lose.")
            else:
                print("You draw.")
            break

        else:
            continue

Ответы [ 2 ]

0 голосов
/ 29 апреля 2020
import random
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")

scoreH=0
scoreAI=0
Round=0

def loss():
    global scoreH
    global scoreAI
    scoreH=scoreH+0
    scoreAI=scoreAI+1
def win():
    global scoreH
    global scoreAI
    scoreH=scoreH+1
    scoreAI=scoreAI+0
def draw():
    global scoreH
    global scoreAI
    scoreH=scoreH+0
    scoreAI=scoreAI+0




x=True


while x == True :
    # Choice
    Round=Round+1
    print("Round",Round,"is going to start. ")
    print("1.Rock")
    print("2.Paper")
    print("3.Scissors")
    choice=input("Enter your choice: ").lower()
    IntChoice=random.randint(1,3)


    #Transforming AI_choice from an int to a string
    if IntChoice == 1:
        AI_choice="rock"
    elif IntChoice == 2:
        AI_choice="paper"
    elif IntChoice == 3:
        AI_choice="scissors"

    print(AI_choice)

    # Draw
    if choice==AI_choice:
        draw()
        print("The computer chose",choice,".You draw.")
    # PlayerWins
    elif choice=="paper" and AI_choice=="rock":
        win()
        print("The computer chose",choice,".You win.")
    elif choice=="scissors" and AI_choice=="paper":
        win()
        print("The computer chose",AI_choice,".You win.")
    elif choice=="rock" and AI_choice=="scissors":
        win()
        print("The computer chose",AI_choice,".You win.")
    # AIwins
    elif AI_choice=="paper" and choice=="rock":
        scoreH,scoreAI=loss(scoreH,scoreAI)
        print("The computer chose",AI_choice,".You lose.")
    elif AI_choice=="scissors" and choice=="paper":
        loss()
        print("The computer chose",AI_choice,".You lose.")
    elif AI_choice=="rock" and choice=="scissors":
        loss()
        print("The computer chose",AI_choice,".You lose.")
    else:
        print("Invalid input.")
        #continue
        end=input()
        # Stop Playing
        if end == "stop" or end == "quit":
            x=False
            print("The score is :",scoreH,"-",scoreAI)
            if scoreH > scoreAI:
                print("You win.")
            elif scoreH < scoreAI:
                print("You lose.")
            else:
                print("You draw.")
                break

        else:
            continue

Ожидаемый результат:

Welcome to this game of rock paper scissors against the computer.
Good luck and have fun! Enjoy this game! 
To stop playing, type quit when the round ends.If you want to continue playing, press any key 
Round 1 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 2 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
paper
The computer chose paper .You draw.
Round 3 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: scissors
paper
The computer chose paper .You win.
Round 4 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 5 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 6 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 7 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 8 is going to start. 
1.Rock
2.Paper
3.Scissors
Enter your choice: 
paper
Invalid input.
stop
The score is : 4 - 2
You win.
0 голосов
/ 29 апреля 2020

Они действительно вызываются, но они изменяют локальную переменную внутри себя.

Чтобы изменить значения, сделайте что-то вроде этого:

def loss(scoreAI):
     return scoreAI+1


scoreAI = loss(scoreAI)

На самом деле, функции действительно просты и в некоторых случаях вы добавляете 0, что равносильно тому, что вы ничего не делаете, поэтому я бы не стал делать для этого функции. Это намного проще:

#Win
scoreH += 1

#Loss
scoreAI += 1

и вам ничего не нужно для розыгрыша.

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...