簡體   English   中英

我將如何使我的Python評分系統工作?

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

我一直在學習在線課程,我試圖想出一些我可以創造的東西來“測試”我自己,因為我想出了一個石頭剪刀游戲。 它運作良好所以我決定嘗試添加一種跟蹤你的分數與計算機的方法。 沒那么順利。

這就是我所擁有的:

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

我在某處讀到全局變量可以起作用但通常不贊成。 不知道為什么然后我不能說他們'= 0因此無法讓它工作。 將ai_score和user_score放在newgame()中不起作用,因為每次重新運行時它都會將其設置為0。 任何幫助將非常感激。

作為一個快速的額外說明,第二個

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

在main()似乎總是執行並總是說“1不是一個選項”,我不知道它為什么這樣做。 我會假設與while循環有關,但我需要它們來保持運行,所以解釋為什么以及如何修復將是偉大的。 在一天結束時,我只是在這里了解更多。

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

課程很精彩。 __init__是此類的構造函數。 它基本上使對象立即為類,並將變量設置為您想要的。 game_object = newgame()生成類對象並將其存儲到game_object中。 要獲取game_object的類變量,我們使用game_object.ai_score 由於您創建了一個類對象,因此它的類變量仍然在您創建的對象的范圍內,即使它可能在您的函數之外。 通常,如果我需要在函數之外使用變量,並且很想使用Global,我會創建一個類。 在某些情況下你不會想要這個,但我個人並沒有遇到過這個。 此外,您可能希望查看評論中有關使用字典作為選項的內容。 還有其他問題嗎?

編輯:

要回答關於print('%s is not an option' % option)的新問題print('%s is not an option' % option)總是在運行,因為在你的代碼中你有if option == '1':然后if option == '2':你想要選項2是elif。 我在我的代碼中修復了它。 如果語句是塊。 因為你開始了一個新的if,否則先沒先檢查是否要查看它是否是一個有效的選項。 從某種意義上說,它超出了它的范圍。 所以既然你的代碼基本上是說選項等於1? 它等於2或3或其他什么? 請注意這些是兩個不同的問題?

似乎變量option不是'1',對吧? 好吧,那是因為函數input不返回字符串,而是返回integer 你可以通過在這個程序中添加一點跟蹤來看到這一點。

print (option, type (option))

在設置了變量選項的行之后。

這將告訴您變量選項的類型,在這種情況下它是一個整數。 首先,你需要替換字符串的比較(比如if option == '1':通過與整數的比較,即: if option == 1: .

至於第二個問題:在函數內聲明或賦值的變量僅存在於該函數的范圍內。 如果你需要在具有外部作用域的函數內使用變量,那么它應該在函數內部重新聲明為global (即使它們“不受歡迎” - 並且有很好的理由)。 def newgame():的開頭def newgame():你需要再次聲明你的全局變量: global ai_score, user_score 您還可以使用類來熟悉面向對象的編程並編寫更好的代碼。 此程序還有其他錯誤,但我相信你會發現。

至少有一個問題是:你的主要是......如果......如果... elif ...其他。 第二個可能需要是一個elif。 提示:當您遇到控制流問題時,將print語句放在每個控制分支中,打印出控制變量以及可能相關的所有其他內容。 這告訴你正在采取哪個分支 - 在這種情況下,哪個分支,復數。

你沒有確切地說出保持分數的問題是什么,但我想這是在賦值之前引用的變量行的異常。 如果是這樣,你應該把“global ai_score”放在函數的頂部。 發生了什么事情,Python可以但不喜歡識別函數內部正在使用的函數之外的變量。 你必須推動一下。 考慮:

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

順便說一下,對於新手來說,你的代碼一點都不差。 我見過很多,甚至更糟! 對於它的價值,我不認為全局變量對於像這樣的小型丟棄程序是不利的。 一旦你有兩個程序員,或兩個線程,或兩個月之間的程序工作會話,全局變量肯定會導致問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM