程序是否在无限函数中循环?

时间:2019-05-08 17:20:20

标签: python

目前正在为基本的python类从事Rock Paper Scissors游戏。在过去的一周中,我一直在研究它,因为我查找了如何制作基本的python游戏,偶然发现此处的一篇文章,然后转为结束。虽然不知道为什么,但是它一直循环播放。我也想保持类似的结构,因为我的老师要求我保持这种结构。

我尝试过更改cpu_rand和cpu_choice,并将函数result()放在不同的位置,但是也没有用。

customerToken() {
    const route = `${this.route}/oauth/token`;
    const headers = {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    const body = new URLSearchParams();
    body.append("grant_type", "client_credentials");
    body.append("client_id", this.clientId);
    body.append("client_secret", this.clientSecret);
    body.append("scope", `customer=${this.costumerEmail}`);
    console.log(route, headers, body);
    return axios.post(route, body, {headers: headers})
        .then(res => {
            return Promise.resolve(res);
        })
        .catch(err => {
            return Promise.reject(err.response);
        });
}

我希望返回的结果是result函数下的所有内容,因此,如果player_choice == cpu_choice,它将打印出该结果下的内容。而是循环回到“岩石,纸张还是剪刀?”

3 个答案:

答案 0 :(得分:0)

您从未在代码中调用过结果函数,因此它从未运行过。

答案 1 :(得分:0)

您没有致电results()。而且player_choice和cpu_choice是playgame()中的局部变量。

import random #import random module
import sys #import system module
def playgame():
    while True:
        player_choice = input("Rock, Paper, or Scissors?")
        cpu_rand = random.randint(1,3) #Generate random integer 1-3
        cpu_choice = None
        if cpu_rand == 1: #if cpu_choice = 1, cpu_choice = "Rock"
            cpu_choice = "Rock"
        elif cpu_rand == 2: #if cpu_choice = 2, cpu_choice = "Scissors"
            cpu_choice = "Scissors"
        elif cpu_rand == 3: #if cpu_choice = 3, cpu_choice = "Paper"
            cpu_choice = "Paper"
        results(player_choice, cpu_choice)
def results(player_choice, cpu_choice): #check results of player choice v computer choice
    play_again = None #Sets this to null for future reference, for asking if playing again.
    if(player_choice == cpu_choice):    #Tie
        print("It's a Tie")
        play_again = input("Retry?")
    #Rock Outcomes
    elif(player_choice == "Rock" and cpu_choice == "Scissors"):
        print("You Win!")
        play_again = input("Play again?")
    elif(player_choice == "Rock" and cpu_choice == "Paper"):
        print("You Lose!")
        play_again = input("Play again?")
    #Paper Outcomes
    elif(player_choice == "Paper" and cpu_choice == "Scissors"):
        print("You Lose!")
        play_again = input("Play again?cpu")
    elif(player_choice == "Paper" and cpu_choice == "Rock"):
        print("You Win!")
        play_again = input("Play again?")
    #Scissors Outcomes
    elif(player_choice == "Scissors" and cpu_choice == "Rock"):
        print("You Lose!")
        play_again = input("Play again?")
    elif(player_choice == "Scissors" and cpu_choice == "Paper"):
        print("You Win!")
        play_again = input("Play again?")

    if play_again == "Yes": #if elif play again statements, from if/elif statements, play_again is changed to an input
        playgame()
    elif play_again == "No":
        print("You Lose!")
        sys.exit()
    else:
        print("Invalid Command")
        play_again = input("play again?")
        return play_again
    results()

def start():
    while True:
        gamestart = input("You ready to play some Rock, Paper, Scissors? (y/n)")
        if gamestart == "y":
                playgame()
                return gamestart
        elif gamestart == "n":
            print("Game Over!")
            break
        else:
            print("Invalid Command")
start()

答案 2 :(得分:0)

您的代码是如此密集和重复,我可以建议另一种方法吗?:

import random
wins = [
    ('paper', 'rock'),   # paper wins over rock
    ('rock', 'scissors'),
    ('scissors', 'paper'),
]
items = ['rock', 'paper', 'scissors']

def computer_choice():
    return random.choice(items)

def player_choice():
    for i, item in enumerate(items):
        print i, item
    while 1:
        choice = input("choose [0..%d]: " % (len(items)-1))
        if 0 <= choice < len(items):
            break
    return items[choice]

while 1:
    cpu = computer_choice()
    human = player_choice()
    print "CPU: %s, HUMAN: %s" % (cpu, human)
    if cpu == human:
        print 'tie..'
    elif (cpu, human) in wins:
        print "CPU wins."
    else:
        print "HUMAN wins."
    again = raw_input("play again? [q to quit]: ")
    print
    if again.lower() == 'q':
        break

示例会话:

0 rock
1 paper
2 scissors
choose [0..2]: 0
CPU: scissors, HUMAN: rock
HUMAN wins.
play again? [q to quit]:

0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: paper, HUMAN: paper
tie..
play again? [q to quit]:

0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: scissors, HUMAN: paper
CPU wins.
play again? [q to quit]:

要使该游戏演奏石头,纸,剪刀,蜥蜴,麻子(https://bigbangtheory.fandom.com/wiki/Rock,_Paper,_Scissors,_Lizard,_Spock),唯一的更改是:

wins = [
    ('scissor', 'paper'),    # Scissors cuts Paper 
    ('paper', 'rock'),       # Paper covers Rock 
    ('rock', 'lizard'),      # Rock crushes Lizard 
    ('lizard', 'spock'),     # Lizard poisons Spock 
    ('spock', 'scissors'),   # Spock smashes Scissors
    ('scissors', 'lizard'),  # Scissors decapitates Lizard
    ('lizard', 'paper'),     # Lizard eats Paper
    ('paper', 'spock'),      # Paper disproves Spock
    ('spock', 'rock'),       # Spock vaporizes Rock
    ('rock', 'scissors'),    # (and as it always has) Rock crushes Scissors 
]
items = ['rock', 'paper', 'scissors', 'lizard', 'spock']

样品运行

0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 4
CPU: scissors, HUMAN: spock
HUMAN wins.
play again? [q to quit]:

0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 2
CPU: spock, HUMAN: scissors
CPU wins.
play again? [q to quit]: