如何将一个类合并到Mastermind的代码中?

时间:2018-04-30 22:20:10

标签: python class

我坚持如何在这段代码中实现一个类。我对编码很新,这是我的第一个项目。玩家应该尝试猜测计算机生成的颜色序列,而我在实现课程时遇到了麻烦。

我也对我的尝试和除了声明感到有些困惑。即使玩家输入错误,我也会努力保持代码的正常运行,但不要将其视为猜测而我无法解决这个问题。

基本程序有效,但我试图让它更简洁,更少混淆,可能会把它的大块变成一个函数或类。

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

1 个答案:

答案 0 :(得分:0)

您的代码实际上非常适合您的第一个项目,所以非常荣幸!你已经完成了一个很好的工作,命名你的变量,有一些有意义的评论,并正确使用空格(虽然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语句,而不是完全脱离循环,它只是回到whilefor或者你有什么。

将它放入一个类中并不那么简单。说实话,我不确定你是否需要这么多,因为代码是可读的!但我可以开始的地方,正在考虑封装当前的游戏状态:

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_guessout_of_guesses :)这有助于将用户输入与游戏逻辑以及您打印出来的内容分开。它不是所有的方式 - 例如它需要做更多的工作才能让它更容易放入图形界面而不是基于文本的界面 - 但它更接近。

你可以争论正确地做这件事的正确方法,你可以查看编辑历史记录,看看我在编写这篇文章的过程中经历的一些变化 - 有时你不会&#39直到你离开一点之后才看东西。这有帮助吗?