[英]How to incorporate a class into this code for Mastermind?
我對如何在此代碼中實現一個類感到困惑。 我對編碼非常陌生,這是我的第一個項目。 玩家應該嘗試猜測計算機生成的顏色序列,而我在實現類時遇到了麻煩。
我對自己的嘗試和除外聲明也感到有些困惑。 即使播放器輸入錯誤,我也會嘗試保持代碼運行,但不能將其視為猜測,我無法弄清楚。
基本程序可以工作,但是我試圖使它更簡化和減少混亂,可能使其中很大一部分成為函數或類。
'''
-------- MASTERMIND --------
'''
from random import choice, sample #importing these for list generation and list randomization
game_active = True
color_choices = ["r","g","b","y","o","p"] #choices for the player and computer
player_color_guess = ["","","",""] #player inputed colors
computer_color_guess = [choice(color_choices),choice(color_choices),choice(color_choices),choice(color_choices)] #generates random 4 choices for the computer
guesses = 0 #keeps track of number of guesses
def you_win(): #function for winning the game
return("You beat the codemaker in " + str(guesses) + " guesses! Great job!")
return("Press any key to exit")
def clean_list(ugly_list): #function that cleans the brackets and other symbols from a list
return(str(ugly_list).replace(',','').replace('[','').replace(']','').replace('\'',''))
print("Welcome to Mastermind!\n\n----------------------\n\nI will make a code of four colors: \nRed(r)\nGreen(g)\nBlue(b)\nYellow(y)\nOrange(o)\nPurple(p)\nGuess the combination of colors. If you get the correct color and the correct place you will get a '+', if you guess \nthe correct color and the wrong place you will get a '~', otherwise you will get a '-'. \nThe position of the symbols do not correlate to the positions of the colors.")
while game_active:
#making main loop for the game
player_guess_symbols = []
#this is to store the first output of symbols, not mixed
num_correct = 0 #to store number of correct guesses
'''try:'''
player_color_guess = str(input("\nInput four colors, separated by a comma.\n>>> ").split(',')) #actual player input
guesses += 1 #every time the player does this it adds one to guess variable
'''except ValueError:
print("{} is not a valid input.".format(player_color_guess))'''
for clr in range(0,4): #looping through first four numbers: 0,1,2,3
if computer_color_guess[clr] == player_color_guess[clr]: #takes the index clr and compares it to the player guess
player_guess_symbols.append("+")
num_correct += 1
elif computer_color_guess[clr] in player_color_guess: #checks if computer guess is in player guess
player_guess_symbols.append("~")
else:
player_guess_symbols.append("-")
if guesses > 10: #this is to check the number of guesses, and see if the player wins
print("You failed to guess the code in 8 guesses or under! The correct code was " + clean_list(computer_color_guess) + ". Press any key to exit")
break #not sure if this is the right place for a break statement
player_guess_symbols_mixed = sample(player_guess_symbols, len(player_guess_symbols))
#this mixes the symbol output each time so the placement of the symbols is not a pattern
if num_correct > 3: #checks of player wins
print(you_win())
print(clean_list(player_guess_symbols_mixed))
實際上,您的第一個項目的代碼格式非常正確,因此非常贊! 在命名變量,添加有意義的注釋以及正確使用空格方面,您做得非常出色(盡管Python迫使您做最后一件事,但這仍然很關鍵)。 保持良好的工作!
通常,這種事情並不完全適合Stack Overflow,但我將嘗試為您提供一些技巧。
關於您的try和except,您可以將其包裝在另一個循環中,或者使用continue
語句:
try:
player_color_guess = str(input("\nInput four colors, separated by a comma.\n>>> ").split(',')) #actual player input
guesses += 1 #every time the player does this it adds one to guess variable
except ValueError:
print("{} is not a valid input.".format(player_color_guess))
continue # go back to while
有時使用continue
可能會導致意大利面條,但是在這種情況下,我認為避免額外的縮進會更簡單。 它的工作原理與break
語句類似,只是它沒有完全脫離循環,而只是回到while
或for
或what-have-you。
把它放到一個類中要簡單一些。 老實說,我不確定您是否需要那么多代碼,因為代碼本身是相當可讀的! 但是我可能要開始的地方是封裝當前的游戲狀態:
class GuessState: # could easily call this MastermindState or what-have-you
guesses = 0
computer_guess = []
player_guess = [] # could be a good place to story a history of player guesses
這給您提供了一個非常好的地方來設置用於設置computer_guess
的函數,例如在__init__
函數中:
def __init__(self):
self.computer_guess = [ ... etc ... ]
您還可以在其中放置一些游戲邏輯,以使內容更具可讀性:
def check_player_guess(self, guess):
# check self.computer_guess against guess
# maybe increment self.guesses here too
# maybe return True if the guess was correct?
def scramble_player_guess(self):
return sample(self.player_guess, len(player_guess))
現在,設置和游戲循環可以變得更加簡單:
state = GuessState()
while(game_active):
player_guess = str(input... etc ...) # might also be a good thing to put in a function
if state.check_player_guess(player_guess):
print "win in {}".format(state.guesses)
break
if state.out_of_guesses():
print "lose"
break # is actually pretty reasonable
print state.scramble_player_guess()
當然,您需要實現check_player_guess
和out_of_guesses
:)這有助於將解釋用戶輸入與游戲邏輯以及打印輸出分開。 這不是一路有-例如,它會采取更多的工作,以使其易於在圖形界面下降VS基於文本的一個-但它一點點接近。
您可能還會爭論執行此操作的正確方法,甚至可以查看編輯歷史記錄,以了解我在撰寫本文時所經歷的一些更改,甚至-有時您直到看到為止走了一點之后 有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.