Thread: Help Need ASAP

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    1
    Rep Power
    0

    Help Need ASAP


    I am attending College, in the computer science major. I am having issues programming the MasterMind Game.

    When playing 'Codemaker' i am able to enter in my secret code and the computer will randomly guess my code. But once that happens my score that i have scored for the computer( Which is determined by black and white pegs ) will print out the actual score whether mine score is right or wrong, then start printing out every other possible score.

    The score needs to returned as a string of "b's and w's" so that the Main() function can determined if you have won or not.

    I do not know why this is happening?

    Any help would be appriciated.
    Thanks, D

    Here is my Code:

    from random import *

    def main():
    welcome()
    ans = input("\n\nSo what do you say? would you like to play a game? [y/n] ")
    ans = (ans.lstrip()).lower()[0]
    while ans == 'y':
    blnWon = False
    which = GetRole()
    if which == 'breaker':
    CodeBreaker()
    else : # which = 'maker'
    code = getuserPat()
    cguess = [] # list of guesses computer made
    scores = [] # list of scores computer recieved
    for i in range(10):
    cguess.append(CompGuess(cguess, scores))
    print("%d: Computer guesses: %s %s %s %s"%((i+1), cguess [i] [0],cguess[i] [1], cguess [i] [2], cguess [i] [3]))
    scores.append(HumanScores(cguess [i], code))
    if scores [i] == 'bbbb':
    blnWon = True
    break
    if blnWon:
    print('I won! It was inevitable, really...')
    else:
    print('I lost?!? This is completely unacceptable!')
    ans = input('\n\nWould you like to play another game? [y/n] ' )
    ans = (ans.lstrip()).lower()[0]



    def welcome():
    print("Welcome to Mastermind!")
    print("When asked to play as CodeBreaker you will do the following below")
    print("The Mastermind game will randomly generate a 4 number sequence out of the 6 that are available.\
    Your job is to guess the random sequence within 12 turns.\
    Instructions: The game will ask you for your guesses.\
    Your guess should look like this : 1,6,4,2.\
    The game will return to you 2 clues. It will return the color Black and/or the color White.\
    The color White determines that atleast 1 of your guesses is the right color (not in the right spot)\
    The color Black determines that atleast 1 of your guesses is the right color and in the right spot\
    Using the returned colors your next guesses should be more and more accurate.\
    Remember you have 12 turns. Guess wisely!")
    print("")
    print("")
    print("When asked to play as CodeMaker you will do the following below")
    print("You will generate your own 4 number combination.\
    The computer will try to guess your code in 12 turns. \
    You will need to output the computers score. White = Right number Wrong Place. \
    Black = Right Number in the right place. \
    Good Luck Beating the Computer!")


    def GetRole():
    typ = eval(input("Please type in a 0 for 'CodeBreaker' and 1 is for 'CodeMaker'. :"))
    if typ == 0:
    return ("breaker")
    if typ == 1:
    return ("maker")
    else:
    print("Please enter the interger (0) for 'CodeBreaker' or (1) for 'CodeMaker'.")


    def getPat():
    blnDone = False
    while not blnDone:
    try:
    ans = input("Please enter your 4 digit guess seperated by commas. :")
    anslist = ans.split(',')
    a = eval(anslist[0])
    b = eval(anslist[1])
    c = eval(anslist[2])
    d = eval(anslist[3])
    if ((a > 0 and a < 7) and (b > 0 and b < 7) and (c > 0 and c < 7) and (d > 0 and d < 7)) and \
    ((type(a) == type(2)) and (type(b) == type(2)) and (type(c) == type(2)) and (type(d) == type(2))):
    blnDone=True
    else:
    print ("You have entered an invalid number. Please enter a whole number 1-6!")
    except ValueError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except NameError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except SyntaxError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except TypeError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except:
    print("You have entered an invalid number. Please enter a whole number 1-6!")

    return [a, b, c, d]
    #Elicits four integers from the user in the range [1,2,3,4,5,6]
    #Returns: A list of four integers entered by the user before, from [1,2,3,4,5,6]


    def scorePat(guess, code):
    #For Black
    #B = Correct color, Correct Position
    guess1 = []
    code1 = []
    guess1.extend(guess)
    code1.extend(code)
    score=""
    b=0
    for i in range(4):
    if guess1[i] == code1[i]:
    b = b+1
    guess1[i] = 0
    code1[i] = 0
    # For White
    #W = Correct color, Correct Position
    w=0
    for i in range(4):
    if guess1[i] != 0:
    for j in range(4):
    if guess1[i] == code1[j]:
    code1[j] = 0
    w = w+1
    break
    score1 = w
    score2 = b
    print("White =",score1)
    print("Black =",score2)
    #if score2 == 4:
    #return True
    #else:
    #return False
    #return score2 == 4


    def genPat():
    string =[]
    for i in range(4):
    g=randint(1,6)
    string.append(g)
    return string


    def CodeBreaker():
    blnWon = False
    mypat = genPat()
    for i in range(1,13):
    guess = getPat()
    blnWon = scorePat(guess,mypat)
    if blnWon: break

    if blnWon:
    print("You Won! My pattern was", mypat)
    else:
    print("You Lost. It was inevitable, really...")

    def getuserPat():
    blnDone = False
    while not blnDone:
    try:
    key = input("Please Enter your secret code you want the computer to guess, string of 4(1-6) seperated by commas. :")
    keylist = key.split(',')
    a = eval(keylist[0])
    b = eval(keylist[1])
    c = eval(keylist[2])
    d = eval(keylist[3])
    if ((a > 0 and a < 7) and (b > 0 and b < 7) and (c > 0 and c < 7) and (d > 0 and d < 7)) and \
    ((type(a) == type(2)) and (type(b) == type(2)) and (type(c) == type(2)) and (type(d) == type(2))):
    blnDone=True
    else:
    print ("You have entered an invalid number. Please enter a whole number 1-6!")
    except ValueError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except NameError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except SyntaxError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except TypeError:
    print("You have entered an invalid number. Please enter a whole number 1-6!")
    except:
    print("You have entered an invalid number. Please enter a whole number 1-6!")

    return [a, b, c, d]
    "Please Enter your secret code you want the computer to try and guess"


    def CompGuess (guesslist, key):
    gs = [1,1,1,1]
    if key == []:
    return genPat()
    else:
    for a in range (1,7):
    gs[0] = a
    for b in range(1,7):
    gs[1] = b
    for c in range (1,7):
    gs[2] = c
    for d in range(1,7):
    gs[3] = d
    x=0
    for i in range(len(guesslist)):
    if(getScore(gs, guesslist[i]) != key[i] or gs == guesslist[i]) :
    break
    else:
    x=x+1
    if x == len(guesslist):
    return gs


    def getScore(guess,key):
    #For Black
    #B = Correct color, Correct Position
    guess1 = []
    code1 = []
    guess1.extend(guess)
    code1.extend(key)
    score=""
    b=0
    for i in range(4):
    if guess1[i] == code1[i]:
    b = b+1
    guess1[i] = 0
    code1[i] = 0
    # For White
    #W = Correct color, Correct Position
    w=0
    for i in range(4):
    if guess1[i] != 0:
    for j in range(4):
    if guess1[i] == code1[j]:
    code1[j] = 0
    w = w+1
    break
    score1 = w
    score2 = b
    return

    #if score2 == 4:
    #return True
    #else:
    #return False
    #return score2 == 4
    #Postcondition: returns the string or else the string <None> for 0 correct digit


    def HumanScores(pat, code):
    print("Please enter the score for the computer: ")
    try:
    wScore1= eval(input("White ="))
    bScore2= eval(input("Black ="))
    scorePat(pat, code)
    blnDone = False
    while blnDone:
    if wScore1 == score1 and bScore2 == score2:
    blnDone=True
    else:
    print("You are trying to Cheat Me!")
    print("My actual score is : ")
    print("Your Score is White =" , score1)
    print("Your Score is White =" , score2)
    except ValueError:
    print("You have entered an invalid String. Please enter a whole number 1-4 for each colored score!")
    except NameError:
    print("You have entered an invalid String. Please enter a whole number 1-4 for each colored score!")
    except SyntaxError:
    print("You have entered an invalid String. Please enter a whole number 1-4 for each colored score!")
    except TypeError:
    print("You have entered an invalid String. Please enter a whole number 1-4 for each colored score!")
    except:
    print("You have entered an invalid String. Please enter a whole number 1-4 for each colored score!")
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,839
    Rep Power
    480
    Ooh, nice. I constructed a mastermind helper in j. www.jsoftware.com .
    Code:
       PATTERNS=: >,{4#<>:i.6  NB. Cartesian product, 6 things taken 4 at a time with replacement.  All possible patterns.
       black =: +/ .="1        NB. verb to count the number of correct guesses
       all =: (_6+[:+/<.)&(#/.~@:((>:i.6)&,))  NB. counts all correct "colors" 1 through 6
       white =: (all - black)"1
    
       $ PATTERNS  NB. how many patterns are possible?
    1296 4
    
       6^4  NB. oddly enough, that's 6 raised to the fourth power.
    1296
    
    
       A=:1 2 3 4&((1=white)*.(1=black))Filter PATTERNS   NB. A are the possibilities
    
       B=:1 5 6 3&((1=white)*.(1=black))Filter A          NB. 1 5 6 3 also had 1 black and 1 white peg
    
       [C=:6 5 2 4&((0 = white) *. (2 = black))Filter B   NB. show the remaining possibilities based on the score of guess 6 5 2 4
    3 5 4 4
    3 5 5 4
    4 5 1 4
    5 5 1 4
    6 1 6 4
    6 2 2 3
    6 3 6 4
       [D=:4 5 1 4&((0=white)*.2=black)Filter C   NB. guess one of the remaining.
    3 5 5 4
    which goes hand-in-hand with the game:
    Code:
    Would you like to play another game? [y/n] y
    Please type in a 0 for 'CodeBreaker' and 1 is for 'CodeMaker'. :0
    Please enter your 4 digit guess seperated by commas. :1,2,3,4
    White = 1
    Black = 1
    Please enter your 4 digit guess seperated by commas. :1,5,6,3
    White = 1
    Black = 1
    Please enter your 4 digit guess seperated by commas. :6,5,2,4
    White = 0
    Black = 2
    Please enter your 4 digit guess seperated by commas. :4, 5, 1, 4
    White = 0
    Black = 2
    Please enter your 4 digit guess seperated by commas. :3, 5, 5, 4
    White = 0
    Black = 4
    Please enter your 4 digit guess seperated by commas. :
    I won the game of mastermind, clearly I got a score of 4 black pegs. The mastermind game should have indicated I won. Let's fix that.

    Code:
       NB. For completeness
       Filter
    (#~`)(`:6)
    OK, looks like there was code for that already, we just need to remove some comments. Let's fix something else. getPat and getuserPat can be condensed to a single function
    Code:
    def getPat(prompt):
        while True:
            try:
                ans = input(prompt)
                tup = eval(ans)
                if (len(tup)==4) and all((0<a<7)and(type(a) is type(2)) for a in tup):
                    break
            except:
                pass
            print("You have entered an invalid number. Please enter a whole number 1-6!")
    
        return list(tup)                      # probably the tuple would work.
            #Elicits four integers from the user in the range [1,2,3,4,5,6]
            #Returns: A list of four integers entered by the user before, from [1,2,3,4,5,6]
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo