"global" 剪刀石头布游戏中的头痛

"global" headache in Rock, Paper, Scissors game

我正在尝试编写 python 与水、蛇和枪游戏(剪刀石头布)相关的代码。

如果我使用这个代码:

import random
usscore = 0
pcscore = 0

wsg = ["Water", "Snake", "Gun"]
inp = [1,2,3]
wsginputT = 0
wsginpw = ""

def wsgf(wsginpw,compran,pcscore,wsginput,usscore):
    if wsginpw == compran:
        print("AARGH its a draw")
        pass
    else:
        if wsginput == 1 and compran == wsg[1]:#WATER VS SNAKE
            print("LOLLL")
            print("HAHA Snake drunk all the water")
            pcscore = pcscore +1
        else:
            if wsginput == 1 and compran == wsg[2]:#WATER VS GUN
                print("Hmmmm will see ya next time! ")
                print("Gun had no chance against WATER")
                usscore = usscore + 1
            else:
                if wsginput == 2 and compran == wsg[0]:#SNAKE VS WATER
                    print("Hmmmm will see ya next time! ")
                    print("HUH Your snake drunk all the water")
                    usscore = usscore + 1
                else:
                    if wsginput == 2 and compran == wsg[2]:#SNAKE VS GUN
                        print("LOLLL")
                        print("HAHA My Gun killed your snake")
                        pcscore = pcscore + 1
                    else:
                        if wsginput == 3 and compran == wsg[0]:#GUN VS WATER
                            print("LOLLL ")
                            print("HAHA your gun is drowned in water!")
                            pcscore = pcscore + 1
                        else:
                            if wsginput == 3 and compran == wsg[1]:#GUN VS SNAKE
                                print("Hmmmm will see ya next time!")
                                print("Not Fair my snake was killed by your gun")
                                usscore = usscore + 1
    print("Pc score",pcscore, "User Score", usscore)

for ten in range(10):
    while True:
        try:
            wsginput = int(input("""Please enter
                             1 FOR WATER
                             2 FOR SNAKE
                             3 FOR GUN\n"""))
            if wsginput in inp:
                break
            else:
                print("Please enter value between 1 and 3 inclusive")
                continue

        except:
            print("Please enter a valid integer")
            continue

    wsginpw = wsg[wsginput-1]
    # print(wsginpw)

    compran = random.choice(wsg)
    # print(compran)
    wsgf(wsginpw,compran,pcscore,wsginput,usscore)

print("Your score is ", usscore)
print("Computer's score is ", pcscore)
if usscore > pcscore:
    print("You Won")
else:
    print("You Lose")

我最后得到的分数是0。你可以 运行 它。

通过引入global函数和代码运行顺利解决了问题但是我记得有人说不要使用global问题Headbutting UnboundLocalError (blah…blah…blah)

global的代码如下:

import random
usscore = 0
pcscore = 0

wsg = ["Water", "Snake", "Gun"]
inp = [1,2,3]
wsginputT = 0
wsginpw = ""

def wsgf():
    global wsginpw
    global compran
    global pcscore
    global wsginput
    global usscore

    if wsginpw == compran:
        print("AARGH its a draw")
        pass
    else:
        if wsginput == 1 and compran == wsg[1]:#WATER VS SNAKE
            print("LOLLL")
            print("HAHA Snake drunk all the water")
            pcscore = pcscore +1
        else:
            if wsginput == 1 and compran == wsg[2]:#WATER VS GUN
                print("Hmmmm will see ya next time! ")
                print("Gun had no chance against WATER")
                usscore = usscore + 1
            else:
                if wsginput == 2 and compran == wsg[0]:#SNAKE VS WATER
                    print("Hmmmm will see ya next time! ")
                    print("HUH Your snake drunk all the water")
                    usscore = usscore + 1
                else:
                    if wsginput == 2 and compran == wsg[2]:#SNAKE VS GUN
                        print("LOLLL")
                        print("HAHA My Gun killed your snake")
                        pcscore = pcscore + 1
                    else:
                        if wsginput == 3 and compran == wsg[0]:#GUN VS WATER
                            print("LOLLL ")
                            print("HAHA your gun is drowned in water!")
                            pcscore = pcscore + 1
                        else:
                            if wsginput == 3 and compran == wsg[1]:#GUN VS SNAKE
                                print("Hmmmm will see ya next time!")
                                print("Not Fair my snake was killed by your gun")
                                usscore = usscore + 1
    print("Pc score",pcscore, "User Score", usscore)

for ten in range(10):
    while True:
        try:
            wsginput = int(input("""Please enter
                             1 FOR WATER
                             2 FOR SNAKE
                             3 FOR GUN\n"""))
            if wsginput in inp:
                break
            else:
                print("Please enter value between 1 and 3 inclusive")
                continue

        except:
            print("Please enter a valid integer")
            continue

    wsginpw = wsg[wsginput-1]
    # print(wsginpw)

    compran = random.choice(wsg)
    # print(compran)
    wsgf()

print("Your score is ", usscore)
print("Computer's score is ", pcscore)
if usscore > pcscore:
    print("You Won")
else:
    print("You Lose")

有人请给我一个不使用 globals 的方法,请记住我是初学者和学习者。如果您使用困难的东西,请也解释一下。 另外,关于如何缩短我的代码的任何提示?

如果您不使用 global,则需要 return 您正在分配的变量,以便调用者可以获得更新后的值。

def wsgf(wsginpw,compran,pcscore,wsginput,usscore):
    if wsginpw == compran:
        print("AARGH its a draw")
        pass
    else:
        if wsginput == 1 and compran == wsg[1]:#WATER VS SNAKE
            print("LOLLL")
            print("HAHA Snake drunk all the water")
            pcscore = pcscore +1
        else:
            if wsginput == 1 and compran == wsg[2]:#WATER VS GUN
                print("Hmmmm will see ya next time! ")
                print("Gun had no chance against WATER")
                usscore = usscore + 1
            else:
                if wsginput == 2 and compran == wsg[0]:#SNAKE VS WATER
                    print("Hmmmm will see ya next time! ")
                    print("HUH Your snake drunk all the water")
                    usscore = usscore + 1
                else:
                    if wsginput == 2 and compran == wsg[2]:#SNAKE VS GUN
                        print("LOLLL")
                        print("HAHA My Gun killed your snake")
                        pcscore = pcscore + 1
                    else:
                        if wsginput == 3 and compran == wsg[0]:#GUN VS WATER
                            print("LOLLL ")
                            print("HAHA your gun is drowned in water!")
                            pcscore = pcscore + 1
                        else:
                            if wsginput == 3 and compran == wsg[1]:#GUN VS SNAKE
                                print("Hmmmm will see ya next time!")
                                print("Not Fair my snake was killed by your gun")
                                usscore = usscore + 1
    print("Pc score",pcscore, "User Score", usscore)
    return pcscore, usscore

for ten in range(10):
    while True:
        try:
            wsginput = int(input("""Please enter 
                             1 FOR WATER
                             2 FOR SNAKE
                             3 FOR GUN\n"""))
            if wsginput in inp:
                break
            else:
                print("Please enter value between 1 and 3 inclusive")
                continue

        except:
            print("Please enter a valid integer")
            continue

    wsginpw = wsg[wsginput-1]
    # print(wsginpw)

    compran = random.choice(wsg)
    # print(compran)
    pcscore, usscore = wsgf(wsginpw,compran,pcscore,wsginput,usscore)

老实说,您的代码读起来很痛苦。创建 rock/paper/scissors 的游戏可以简化为在 3x3 矩阵上比较输入 X 和输入 Y:

# The matrix defines when the user wins (1), when its a draw (0),
# and when the PC wins (-1)
   
           USER 
          R   P   S
      R [ 0,  1, -1 ]
PC    P [-1,  0,  1 ]
      S [ 1, -1,  0 ]

考虑到这一点,这个小游戏可以分为 2 个功能:一个要求输入并检查你是赢还是输,第二个重复第一个游戏一定次数并跟踪得分。

这显然与您的代码有很大不同,但它也是一个更清晰的实现,我希望您能从中学到一些东西。

import random
import numpy as np


def rps():
    """
    Ask for input, and compare to a random choice by the pc.

    Returns
    -------
    int
        -1: PC wins, 0: draw, 1: user wins.
    """
    mapping = dict(rock=0, paper=1, scissors=2)
    win_matrix = np.array(
        [[0, 1, -1],
         [-1, 0, 1],
         [1, -1, 0]])
    
    user_input = input('Rock, Paper or Scissors? ').lower().strip()
    assert user_input in mapping, \
        "Input must be one of 'rock', 'paper' or 'scissors'"
    pc_input = random.choice(['rock', 'paper', 'scissors'])
    
    if win_matrix[mapping[pc_input], mapping[user_input]] == 0:
        print ('Draw')
    elif win_matrix[mapping[pc_input], mapping[user_input]] == 1:
        print ('You win!')
    elif win_matrix[mapping[pc_input], mapping[user_input]] == -1:
        print ('The PC win!')

    return win_matrix[mapping[pc_input], mapping[user_input]]
    
def run(n_times):
    """
    Runs the RPS game a certain number of times and keep track of the score.
    """
    user_score = 0
    pc_score = 0
    
    for k in range(n_times):
        result = rps()
        if result == 1:
            user_score += 1
        elif result == -1:
            pc_score += 1
            
    print (f'The score is: [USER] {user_score} -- [PC] {pc_score}')
    
    return user_score, pc_score

if __name__ == '__main__':
    run(5)

但是每个 win/loose 场景的自定义消息呢?而不是痛苦的 if/elif/else 结构(这甚至不是你的情况,因为你使用了最糟糕的嵌套 if/else 结构),只需定义对应于每个矩阵位置的自定义句子:

sentences = {
    (0, 0): 'Sentence when rock vs rock',
    (0, 1): 'Sentence when user paper vs pc rock',
    ...
    }

然后在第一个函数中使用这个字典和变量 (mapping[pc_input], mapping[user_input])