2017-04-12 3 views
-2

Mastermind Spiel mit "ABCEF" Ich weiß nicht, wie man überprüft, ob es teilweise korrekt ist. Ich muss Rot verwenden, um richtigen Buchstaben und Position zu meinen. Ich benutze Weiß, um richtigen Buchstaben zu bedeuten.Mastermind Python mit "ABCDEF"

import random 

def play_one_round(): 
    N_code=''.join(random.sample("ABCDEF",4)) 
    print (N_code) 
    guess=input("Enter your guess as 4 letters e.g. XXXX:") 
    count_guess= 1 
    while N_code != guess and count_guess < 10: 
      check(N_code,guess) 
      guess=input("Enter your guess as 4 letters e.g. XXXX:") 
      count_guess=count_guess + 1 
      print("This is your",count_guess, "guess") 
      if guess==N_code: 
      print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order. 

def check(N_code,guess): 
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)] 
    for index, char in enumerate(guess): 
     if result[index] !='r': 
      if char in result: 
       result[result.index(char)]='w' 

print(result) 

def Master_m(): 
    print("Welcome to Mastermind!\n") 
    print("Start by Choosing four letters") 
    play_one_round() 
    answer=input("Play Again? ") 
    if answer[0]=='y': 
     Master_m() 

Master_m() 
+0

Ihr Code hat Einzug Probleme tun. Es scheint, dass Sie nicht alles in einen Codeblock geschrieben haben und mit einigen Zeilen wie "rate = ..." ist es nicht klar, ob es in einer Funktion sein sollte oder nicht. Fix diese und wir können es leichter lesen. – tdelaney

+0

oh, und erzähl uns, was schief gelaufen ist und was du gerne sehen würdest, damit wir nicht raten müssen. – tdelaney

+0

Ich bin neu Stack Flow, ich weiß nicht, wie man es formatiert, um richtig zu zeigen. Ich bin wirklich festgefahren. Ich bin neu und wir müssen ein Spiel mit den Alphabeten erstellen. Dies ist, wie weit ich bekommen habe, wie zähle ich teilweise korrekte Antwort, sondern auch die richtige Position, ich muss auch dem Benutzer sagen, dass mit den roten und weißen Pflöcke. Rot bedeutet, dass es die richtigen Buchstaben ist und in der richtigen Position (Reihenfolge) und weiß bedeutet, dass es der richtige Buchstabe ist. – Lewis

Antwort

0

Wenn Sie stecken bleiben, zerlegen Sie in kleinere Stücke und testen Sie diese. Konzentrieren Sie sich auf check, können Sie überprüfen, ob ein Schätzungsschreiben über seinen Index genau mit dem Code übereinstimmt und ob es überhaupt im Code mit in ist. Hier ist ein in sich geschlossenes Beispiel. Beachten Sie, dass ich alles außer dem Problem herausgezogen habe.

Wenn dies für Sie funktioniert, schlage ich vor, ein eigenständiges Beispiel Ihres nächsten Problems zu schreiben, es zu testen, und wenn Sie immer noch feststecken, posten Sie das als eine neue Frage.

def check(N_code, guess): 
    print('code', N_code, 'guess', guess) 
    result = [] 
    # enumerate gives you each letter and its index from 0 
    for index, letter in enumerate(guess): 
     if N_code[index] == letter: 
      # right letter in right position 
      vote = 'red' 
     elif letter in N_code: 
      # well, at least the letter is in the code 
      vote = 'white' 
     else: 
      # not even close 
      vote = 'black' 
     # add partial result 
     result.append('{} {}'.format(letter, vote)) 
    # combine and print 
    print(', '.join(result)) 

check('ABCD', 'ABCD') 
check('DEFA', 'ABCD') 
+0

Ich habe meine Antwort aktualisiert, aber immer noch ein Problem, ich denke, es ist wegen der "Zip". Ich brauche ein x, um den falschen Buchstaben anzuzeigen. – Lewis

1

Ich schrieb vor diesem Alter, aber es wird den Trick

import random 
    import itertools 

    def start(): 
     """ this function is used to initialise the users interaction with the game 
     Primarily this functions allows the user to see the rules of the game or play the game""" 
     print ('Mastermind, what would you like to do now?\n') 
     print ('Type 1 for rules') 
     print ('Type 2 to play') 
     path = input('Type your selection 1 or 2: ') 
     if path == '1': 
      print ('Great lets look at the rules') 
      rules() 
     elif path == '2': 
      print('Great lets play some Mastermind!\n') 
      begingame() 
      start() 
     else: 
      print('that was not a valid response there is only one hidden option that is not a 1 or a 2') 
      start() 

    def rules(): 
     """This just prints out the rules to the user.""" 
     print ('The rules are as follows:\n') 
     print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n') 
     print ('2)You will have 12 attempts to guess the correct number.\n') 
     print ('3)Whites represent a correct number that is not in the correct order\n') 
     print ('4)Reds represent a correct number in the correct order.\n') 
     print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n') 
     print ('6)to WIN you must guess the 4 numbers in the correct order.\n') 
     print ('7)If you run out of guesses the game will end and you lose.\n') 
     print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.') 
     start() 

    def makeRandomWhenGameStarts(): 
     """A random 4 digit number is required this is created as its own 
     variable that can be passed in at the start of the game, this allows the user 
     to guess multiple times against the one number.""" 

     #generate a 4 digit number 
     num = random.sample(range(1,9), 4) 

     #roll is the random 4 digit number as an int supplied to the other functions 
     roll = int(''.join(map(str,num))) 

     return roll 

    def begingame(): 
     """This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is 
     passed in anbd then an exception handling text input is used to ask the user for their guees """ 
     print ('please select 4 numbers') 

     #bring in the random generated number for the user to guess. 
     roll    = makeRandomWhenGameStarts() 
     whiteResults  = [] 
     redResults   = [] 
     collectScore  = [] 
     guessNo    = 0 

     #setup the while loop to end eventually with 12 guesses finishing on the 0th guess. 
     guesses = 12 
     while (guesses > 0): 
      guessNo = guessNo + 1 
      try: 
       #choice = int(2468) #int(input("4 digit number")) 
       choice = int(input("Please try a 4 digit number: ")) 
       if not (1000 <= choice <= 9999): 
        raise ValueError() 
        pass 
      except ValueError: 
       print('That was not a valid number, you lost a turn anyway!') 
       pass 
      else: 
       print ("Your choice is", choice) 

      #Use for loops to transform the random number and player guess into lists 
      SliceChoice = [int(x) for x in str(choice)] 
      ranRoll  = [int(x) for x in str(roll)] 

      #Take the individual digits and assign them a variable as an identifier of what order they exist in. 
      d1Guess = SliceChoice[0:1] 
      d2Guess = SliceChoice[1:2] 
      d3Guess = SliceChoice[2:3] 
      d4Guess = SliceChoice[3:4] 

      #combine the sliced elements into a list 
      playGuess = (d1Guess+d2Guess+d3Guess+d4Guess) 

      #Set reds and whites to zero for while loop turns  
      nRed = 0 
      nWhite = 0 

      #For debugging use these print statements to compare the guess from the random roll 
      # print(playGuess, 'player guess') 
      # print(ranRoll,'random roll') 

      #Use for loops to count the white pegs and red pegs 
      nWhitePegs = len([i for i in playGuess if i in ranRoll]) 
      nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)]) 


      print ('Oh Mastermind that was a good try! ') 

      #Take the results of redpegs and package as turnResultsRed 
      TurnResultsRed = (nRedPegs) 

      #Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite 
      TurnResultsWhite = (nWhitePegs - nRedPegs) #nWhite-nRed 

      #Create a unified list with the first element being the guess number 
      # using guessNo as an index and storing the players choice and results to feedback at the end 
      totalResults = (guessNo,choice , TurnResultsWhite ,TurnResultsRed) 

      # collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses 
      collectScore.append(totalResults) 

      #End the while loop if the player has success with 4 reds  
      if nRed == (4): 
       print('Congratulations you are a Mastermind!') 
       break  

      #Return the results of the guess to the user 
      print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n') 

      #remove 1 value from guesses so the guess counter "counts down" 
      guesses = guesses -1 
      print ('You have', guesses, "guesses left!") 

     #First action outside the while loop tell the player the answer and advise them Game Over 
     print('Game Over!') 
     print('The answer was', roll) 

     #At the end of the game give the player back their results as a list 
     for x in collectScore: 
      print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites') 


    if __name__ == '__main__': 
     start() 
Verwandte Themen