【问题标题】:"global" headache in Rock, Paper, Scissors game剪刀石头布游戏中的“全球”头痛
【发布时间】:2021-09-21 21:49:50
【问题描述】:

我正在尝试编写与水蛇枪游戏(石头、纸、剪刀)相关的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函数解决的问题,代码运行流畅,但我记得有人说不要使用全局有问题Headbutting UnboundLocalError (blah…blah…blah)

globals 的代码如下:

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 的方法,请记住我是初学者,正在学习。如果您使用困难的东西,请解释它。 另外,关于如何缩短我的代码的任何提示?

【问题讨论】:

  • 使用elif 而不是在else 中嵌套if
  • 谢谢,但是全球呢?
  • 没什么,我还没读完你的代码。由于极度嵌套,很难理解。
  • 对不起
  • 如果您有工作代码,我建议您使用Code Review Stack Exchange 对其进行批评并获得改进建议。

标签: python global-variables globals


【解决方案1】:

如果您不使用global,则需要返回您分配的变量,以便调用者可以获取更新后的值。

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)

【讨论】:

    【解决方案2】:

    老实说,您的代码读起来很痛苦。创建一个石头/纸/剪刀游戏可以简化为在 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 ]
    

    考虑到这一点,这个小游戏可以分为两个功能:一个是询问输入并检查您是赢还是输,另一个是重复第一个游戏一定次数并跟踪比分.

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

    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)
    

    但是对于每个赢/输场景的自定义消息呢?而不是痛苦的 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])

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多