简体   繁体   English

石头剪刀布游戏中的“全局”头痛

[英]“global” headache in Rock, Paper, Scissors game

I am trying to write python code related to water, snake and gun game (Rock, Paper, Scissor).我正在尝试编写与水、蛇和枪游戏(岩石、纸、剪刀)相关的 python 代码。

If I use this code:如果我使用此代码:

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")

The score I receive at end is 0 .我最后收到的分数是0 You can run it.你可以运行它。

The problem solved by introducing global function and code runs smoothly but I remember someone saying not to use global in question Headbutting UnboundLocalError (blah…blah…blah)通过引入global函数和代码解决的问题运行顺利,但我记得有人说不要使用全局问题Headbutting UnboundLocalError (blah…blah…blah)

The code with global s is as follows:带有global s 的代码如下:

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")

Someone please find me a way to not to use global s and please remember I am a beginner and learning.有人请给我找到一种不使用global的方法,请记住我是初学者和学习者。 If you use something difficult please explain it as well.如果你使用一些困难的东西,也请解释一下。 Also, any tips on how to shorten my code?另外,关于如何缩短我的代码的任何提示?

If you don't use global you need to return the variables that you're assigning, so the caller can get the updated values.如果您不使用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)

Honestly, your code is a pain to read.老实说,你的代码读起来很痛苦。 Creating a game of rock/paper/scissors can be simplified to comparing an input X with an input Y, on a 3x3 matrix:创建石头/纸/剪刀游戏可以简化为在 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 ]

With that in mind, this little game can be divided into 2 functions: one which ask an input and check if you win or loose, and a second which repeats this first one a certain number of time and keep track of the score.考虑到这一点,这个小游戏可以分为两个功能:一个是询问输入并检查你是赢还是输,第二个是重复第一个游戏一定次数并跟踪分数。

This is obviously way different from your code, but it's also a cleaner implementation from which I hope you may learn something.这显然与您的代码不同,但它也是一个更清晰的实现,我希望您可以从中学到一些东西。

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)

But what about the custom messages for each win/loose scenario?但是每个获胜/失败场景的自定义消息呢? Instead of a painful if/elif/else structure (which is not even your case as you used a far worst nested if/else structure), simply define the custom sentence corresponding to each matrix position:而不是痛苦的 if/elif/else 结构(这甚至不是你的情况,因为你使用了最糟糕的嵌套 if/else 结构),只需定义与每个矩阵位置对应的自定义句子:

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

And then use this dictionary in the first function with the variable (mapping[pc_input], mapping[user_input]) .然后在第一个函数中使用这个字典和变量(mapping[pc_input], mapping[user_input])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM