Saturday, May 09, 2015

Python number game

__author__ = 'Baris Gomleksizoglu'

import random


def test_number(guess, real):
    if guess == real:
        return 4, 0

    plus = 0
    minus = 0
    for gi, gx in enumerate(guess):
        for ri, rx in enumerate(real):
            if gi == ri and gx == rx:
                plus += 1
            elif gx == rx:
                minus += 1

    return plus, minus

def validate_hint(strHint):
    if len(strHint) != 4 or strHint[0] != "+" or strHint[2]!="-":
        print("Hint should be exact 4 characters and should start with + and continue with -")
        print("Example: +2-1 or +1-0 or +0-0 or +0-1")
        return False

    return True

# Main program
# only add numbers like 1023, but not 1001
ALL_NUMS = [str(x)
            for x in range(1000, 9999)
            if len(set(str(x))) == len(list(str(x)))
        ]

print("Game start, I am holding a number between 1000 to 9999, try to guess!")
print("For each guess, I will give a hint, + numbers means the location is correct")
print("- numbers means it exists but location is not correct.")

computer_number = random.choice(ALL_NUMS)

while True:
    # Game loop
    user_number = input("Enter your guess> ")
    if user_number == "hint":
        print(computer_number)

    result = test_number(user_number, computer_number)

    if result == (4, 0):
        print("Well done, you found the number")
        break

    print("Hint is: +{} -{}".format(*result))

currentNums = ALL_NUMS[:]
counter = 0

print("Now I will guess your number")
print("Enter my hints in the format +n-m without spaces")
print("if the guess not exists, enter zero like +2-0")

while True:
    my_guess = random.choice(currentNums)
    hint = input("My guess is {}, please enter hint>".format(my_guess))

    if not validate_hint(hint):
        continue

    counter += 1
    if hint == "+4-0":
        print("I found it in {} tries".format(counter))
        break

    hintTuple = int(hint[1]), int(hint[3])

    # analyze hint and remove numbers
    new_list = []
    for n in currentNums:
        if test_number(n, my_guess) == hintTuple:
            new_list.append(n)

    if len(new_list) == 0:
        print("Hints are not correct, the number should be one of this values:")
        print(currentNums)
        counter -= 1
    else:
        currentNums = new_list