简体   繁体   English

我将如何使我的Python评分系统工作?

[英]How Would I Go About Making My Python Scoring System Work?

I've been learning through an online course and I was trying to come up with ideas for things I could create to "test" myself as it were so I came up with a rock paper scissors game. 我一直在学习在线课程,我试图想出一些我可以创造的东西来“测试”我自己,因为我想出了一个石头剪刀游戏。 It was working well so I decided to try and add a way of keeping track of your score vs the computer. 它运作良好所以我决定尝试添加一种跟踪你的分数与计算机的方法。 Didn't go so well. 没那么顺利。

Here's what I have: 这就是我所拥有的:

from random import randint

ai_score = 0
user_score = 0

def newgame():
    print('New Game')
    try:
        while(1):
            ai_guess = str(randint(1,3))
            print('\n1) Rock \n2) Paper \n3) Scissors')
            user_guess = input("Select An Option: ")

            if(user_guess == '1'):
                print('\nYou Selected Rock')

            elif(user_guess == '2'):
                print('\nYou Selected Paper')

            elif(user_guess == '3'):
                print('\nYou Selected Scissors')

            else:
                print('%s is not an option' % user_guess)

            if(user_guess == ai_guess):
                print('Draw - Please Try Again')
            elif (user_guess == '1' and ai_guess == '2'):
                print("AI Selected Paper")
                print("Paper Beats Rock")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '1' and ai_guess == '3'):
                print("AI Selected Scissors")
                print("Rock Beats Scissors")
                print("You Win!")
                user_score += 1
                break
            elif (user_guess == '2' and ai_guess == '1'):
                print("AI Selected Rock")
                print("Paper Beats Rock")
                print("You Win!")
                user_score += 1
                break
            elif (user_guess == '2' and ai_guess == '3'):
                print("AI Selected Scissors")
                print("Scissors Beats Paper")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '3' and ai_guess == '1'):
                print("AI Selected Rock")
                print("Rock Beats Scissors")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '3' and ai_guess == '2'):
                print("AI Selected Paper")
                print("Scissors Beats Paper")
                print("You Win!")
                user_score += 1
                break
            else:
                pass
                break

    except KeyboardInterrupt:
        print("\nKeyboard Interrupt - Exiting...")
        exit()

#1 = Rock, 2 = Paper, 3 = Scissors


def main():
    while(1):
        print("\n1) New Game \n2) View Score \n3) Exit")
        try:
            option = input("Select An Option: ")

            if option == '1':
                newgame()   
            if option == '2':
                print("\nScores")
                print("Your Score: " + str(user_score))
                print("AI Score: " + str(ai_score))
            elif option == '3':
                print('\nExiting...')
                break
            else:
                print('%s is not an option' % option)
        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()


main()

I read somewhere that global variables can work but are generally frowned upon. 我在某处读到全局变量可以起作用但通常不赞成。 Not sure why but then I can't say they're =0 so couldn't get that to work. 不知道为什么然后我不能说他们'= 0因此无法让它工作。 Putting the ai_score and user_score in the newgame() doesn't work because it sets it to 0 every time you re run. 将ai_score和user_score放在newgame()中不起作用,因为每次重新运行时它都会将其设置为0。 Any help would be much appreciated. 任何帮助将非常感激。

As a quick extra note, the second 作为一个快速的额外说明,第二个

else:
   print('%s is not an option' % option)

in main() always seems to execute and always says "1 is not an option" and I have no idea why it does that. 在main()似乎总是执行并总是说“1不是一个选项”,我不知道它为什么这样做。 I would assume something to do with while loops but I need those to keep it running so an explanation of why and how to fix would be great. 我会假设与while循环有关,但我需要它们来保持运行,所以解释为什么以及如何修复将是伟大的。 At the end of the day, I'm just here to learn more. 在一天结束时,我只是在这里了解更多。

from random import randint

class newgame():

    ai_score = 0
    user_score = 0

    def __init__(self):
        self.ai_score = 0
        self.user_score = 0

    def playgame(self):
        print('New Game')
        try:
            while(1):
                ai_guess = str(randint(1,3))
                print('\n1) Rock \n2) Paper \n3) Scissors')
                user_guess = input("Select An Option: ")

                if(user_guess == '1'):
                    print('\nYou Selected Rock')

                elif(user_guess == '2'):
                    print('\nYou Selected Paper')

                elif(user_guess == '3'):
                    print('\nYou Selected Scissors')

                else:
                    print('%s is not an option' % user_guess)

                if(user_guess == ai_guess):
                    print('Draw - Please Try Again')
                elif (user_guess == '1' and ai_guess == '2'):
                    print("AI Selected Paper")
                    print("Paper Beats Rock")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '1' and ai_guess == '3'):
                    print("AI Selected Scissors")
                    print("Rock Beats Scissors")
                    print("You Win!")
                    self.user_score += 1
                    break
                elif (user_guess == '2' and ai_guess == '1'):
                    print("AI Selected Rock")
                    print("Paper Beats Rock")
                    print("You Win!")
                    self.user_score += 1
                    break
                elif (user_guess == '2' and ai_guess == '3'):
                    print("AI Selected Scissors")
                    print("Scissors Beats Paper")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '3' and ai_guess == '1'):
                    print("AI Selected Rock")
                    print("Rock Beats Scissors")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '3' and ai_guess == '2'):
                    print("AI Selected Paper")
                    print("Scissors Beats Paper")
                    print("You Win!")
                    self.user_score += 1
                    break
                else:
                    pass
                    break

        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()

    #1 = Rock, 2 = Paper, 3 = Scissors


def main():
    game_object = newgame()
    while(1):
        print("\n1) New Game \n2) View Score \n3) Exit")
        try:
            option = input("Select An Option: ")

            if option == '1':
                game_object.playgame()
            elif option == '2':
                print("\nScores")
                print("Your Score: " + str(game_object.user_score))
                print("AI Score: " + str(game_object.ai_score))
            elif option == '3':
                print('\nExiting...')
                break
            else:
                print('%s is not an option' % option)
        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()


main()

Classes are wonderful. 课程很精彩。 __init__ is the constructor for this class. __init__是此类的构造函数。 It basically makes the object instant for the class and sets the variable to what you want. 它基本上使对象立即为类,并将变量设置为您想要的。 game_object = newgame() makes the class object and stores it into game_object. game_object = newgame()生成类对象并将其存储到game_object中。 To get the class variable of the game_object, we use game_object.ai_score . 要获取game_object的类变量,我们使用game_object.ai_score Since you made a class object it's class variables are still in scope of the object you made, even though it might be outside of your function. 由于您创建了一个类对象,因此它的类变量仍然在您创建的对象的范围内,即使它可能在您的函数之外。 Generally, if I need to use a variable outside of a function, and is tempted to use Global, I make a class instead. 通常,如果我需要在函数之外使用变量,并且很想使用Global,我会创建一个类。 There are some cases where you wouldn't want this, but personally I haven't come across one. 在某些情况下你不会想要这个,但我个人并没有遇到过这个。 Also you might want to look into like what the comments were saying about using dictionary as options. 此外,您可能希望查看评论中有关使用字典作为选项的内容。 Any other questions? 还有其他问题吗?

Edit: 编辑:

To answer your new question about print('%s is not an option' % option) always running, is because in your code you had if option == '1': and then if option == '2': You want the option 2 to be elif. 要回答关于print('%s is not an option' % option)的新问题print('%s is not an option' % option)总是在运行,因为在你的代码中你有if option == '1':然后if option == '2':你想要选项2是elif。 I fixed it in my code. 我在我的代码中修复了它。 If statements are in blocks. 如果语句是块。 since you started a new if, the else didn't check first first if to see if it's a valid option. 因为你开始了一个新的if,否则先没先检查是否要查看它是否是一个有效的选项。 It was out of it's scope in a sense. 从某种意义上说,它超出了它的范围。 So since your code was basically saying is option equal to 1? 所以既然你的代码基本上是说选项等于1? is it equal to 2 or 3 or anything else? 它等于2或3或其他什么? notice these are two different questions? 请注意这些是两个不同的问题?

It seems that the variable option is not '1', right ? 似乎变量option不是'1',对吧? Well, that's because the function input does not return a character string, but an integer . 好吧,那是因为函数input不返回字符串,而是返回integer You can see this by adding a little trace in this program. 你可以通过在这个程序中添加一点跟踪来看到这一点。

print (option, type (option))

after a line where the variable option has been set. 在设置了变量选项的行之后。

This will tell you of what type is the variable option, in that case it is an integer. 这将告诉您变量选项的类型,在这种情况下它是一个整数。 So first, you need to replace the comparisons against strings (like if option == '1': by comparisons against integers, that is : if option == 1: . 首先,你需要替换字符串的比较(比如if option == '1':通过与整数的比较,即: if option == 1: .

As for the second question : variables declared or assigned inside of a function exist for the scope of that function only. 至于第二个问题:在函数内声明或赋值的变量仅存在于该函数的范围内。 If you need to use a variable inside a function that has outer scope, it should be redeclared inside the function as global (even if they are "frowned upon" -- and there are good reasons for this). 如果你需要在具有外部作用域的函数内使用变量,那么它应该在函数内部重新声明为global (即使它们“不受欢迎” - 并且有很好的理由)。 At the beginning of def newgame(): you need to declare again your global variables : global ai_score, user_score . def newgame():的开头def newgame():你需要再次声明你的全局变量: global ai_score, user_score You can also use classes to get familiar with object oriented programming and write nicer code. 您还可以使用类来熟悉面向对象的编程并编写更好的代码。 There is an other error left in this program, but I'm sure you'll find out. 此程序还有其他错误,但我相信你会发现。

At least one problem is this: your main has if...if...elif...else. 至少有一个问题是:你的主要是......如果......如果... elif ...其他。 The second if probably needs to be an elif. 第二个可能需要是一个elif。 Tip: When you have a flow-of-control problem, put print statements inside each control branch, printing out the control variable and everything else that might possibly be relevant. 提示:当您遇到控制流问题时,将print语句放在每个控制分支中,打印出控制变量以及可能相关的所有其他内容。 This tells you which branch is being taken -- in this case, which branches, plural. 这告诉你正在采取哪个分支 - 在这种情况下,哪个分支,复数。

You don't say exactly what the problem was with keeping score, but I imagine it was an exception along the lines of variable referenced before assignment. 你没有确切地说出保持分数的问题是什么,但我想这是在赋值之前引用的变量行的异常。 If so, you should put "global ai_score" somewhere at the top of the function. 如果是这样,你应该把“global ai_score”放在函数的顶部。 What's going on is that Python can, but doesn't like to, recognize variables outside a function that are being used inside the function. 发生了什么事情,Python可以但不喜欢识别函数内部正在使用的函数之外的变量。 You have to push a little. 你必须推动一下。 Consider: 考虑:

>>> bleem = 0
>>> def incrbleem():
...   bleem += 1
...
>>> incrbleem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in incrbleem
UnboundLocalError: local variable 'bleem' referenced before assignment
>>> def incrbleem():
...   global bleem
...   bleem += 1
...
>>> bleem
0
>>> incrbleem()
>>> bleem
1

By the way, your code isn't bad at all, for a newbie. 顺便说一下,对于新手来说,你的代码一点都不差。 I've seen much, much worse! 我见过很多,甚至更糟! For what it's worth, I don't think global variables are bad for a small, throw-away program like this. 对于它的价值,我不认为全局变量对于像这样的小型丢弃程序是不利的。 Once you have two programmers, or two threads, or two months between work sessions on the program, globals can definitely cause problems. 一旦你有两个程序员,或两个线程,或两个月之间的程序工作会话,全局变量肯定会导致问题。

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

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