I am a C#/.Net developer and have decided it is time to branch out and really learn Python. I started with a simple implementation of a Mastermind-esque game. Any comments about the code would be greatly appreciated. I already know the gameplay isn't perfect, but it was just a quick attempt. I also am aware that there isn't much user input checking, but again, quick attempt.
import random
class Game(object):
def run(self):
guesses = []
game_states = []
length = int(input("Choose length of code to break: "))
code = [random.randint(0, 9) for i in range(length)]
def take_guess():
correct_guess_length = False
while not correct_guess_length:
guess = input("Guess a number of length {0}: ".format(length))
if len(guess) != length:
print("Guesses must be a number of length {0}.".format(length))
else:
correct_guess_length = True
return guess
def check_guess(guess):
return all([x == y for x, y in zip(guess, code)])
def evaluate_guess(guess):
new_state = []
for pos, number in enumerate(guess):
if code[pos] == number:
new_state.append(str(number))
elif number in code:
new_state.append("O")
else:
new_state.append("X")
game_states.append(''.join([c for c in new_state]))
def print_game_state():
print()
for guess, state in zip(guesses, game_states):
print("{0}\t{1}".format(guess, state))
correct = False
while not correct:
guess = take_guess()
guesses.append(guess)
guess_as_ints = [int(c) for c in guess]
if not check_guess(guess_as_ints):
evaluate_guess(guess_as_ints)
print_game_state()
else:
print("You guessed the code was {0}! Congratulations!".format(''.join([str(i) for i in code])))
correct = True
if __name__ == '__main__':
game = Game()
game.run()