Python Mastermind Game Troubles

前端 未结 3 872
庸人自扰
庸人自扰 2020-12-22 00:40

I\'m a beginner to Python programming and have come upon an issue with my current assignment. The assignment reads as follows...

  • Your program should secretly g
3条回答
  •  悲&欢浪女
    2020-12-22 01:33

    Very interesting homework I must say. I wish I'd get homework like this one.

    Normally I don't provide full answers to homework but I solved this one for fun and you have tried to solve this on your own so here you go:

    import random
    
    def main():
        print '>> New game started.\n>> Good luck!\n'
        answer = generateAnswer()
        while True:
            userGuess = getUserGuess()
            if userGuess == answer:
                print '>> Congratulations, you won!'
                return
            print '>> The answer you provided is incorrect.\n>> Perhaps this hint will help you: '
            giveFeedback(answer, userGuess)
    
    def generateAnswer():
        digits = [str(x) for x in range(10)]
        answer = ''
        for i in range(4):
            digit = random.sample(digits, 1)[0]
            digits.remove(digit)
            answer += digit
        return answer
    
    def getUserGuess():
        while True:
            guess = raw_input('>> Please enter a 4-digit number: ').strip()
            if len(guess) != 4:
                continue
            guessIsValid = True
            for x in guess:
                if guess.count(x) != 1 or ord(x) not in range(48, 58):
                    guessIsValid = False
                    break
            if guessIsValid:
                return guess
    
    def giveFeedback(answer, guess):
        for i in range(4):
            if guess[i] == answer[i]:
                print 'X',
                continue
            if guess[i] in answer:
                print 'O',
                continue
            print '-',
        print '\n'
    
    if __name__ == '__main__':
        try:
            main()
        except Exception, e:
            print '>> Fatal error: %s' % e
    

    I hope you'll find your answer in this piece of code.

提交回复
热议问题