Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mastermind game
#1
Hello there,
I have to do a sort-of mastermind game, where you have to guess the numbers in an array.
I have no particular problem except when it comes to count how many numbers are in the array, but at the wrong place.
(Note that there is a rule saying numbers can't go above 5)
For example when the answer is 1234 and I type 1115, I need the game to tell me I have 1 correct number but since the only "1" needed is well placed, I also need the game to tell me there are no numbers at the wrong spot

Here's the code:
import random as R
t = [0, 0, 0, 0]
tableauPlacement =[0,0]
global joue
joue = True;
tableauEntree = [0, 0, 0, 0]
compteur = 0;
compteurLose = 0;
choixJoueur = "";
def choix_ordinateur ():
    for i in range (4):
        t[i] = R.randint(1, 5)
        
def choix_utilisateur():
    entree = 0
    print("Entrez un nombre a 4 chiffres svp ? ")
    entree = int(input(""))
    while((entree % 10) > 5 or (entree % 100) >= 60 or entree % 1000 > 600 or entree >= 6000):
        print("n'entrez que des nombres entre 1 et 5 svp:  ")
        entree = int(input(""))
    for i in range(4):
        tableauEntree[3-i] = entree % 10
        tableauEntree[3-i] = int(tableauEntree[3 - i])
        entree = (entree - tableauEntree[3 - i])/10
    print("vous avez donc: ", tableauEntree)

def placement():
    tableauPlacement =[0,0]
    compteurMalPlaces = 0
    compteurBienPlaces = 0
    for i in range(4):
        if (t[i] == tableauEntree[i]):
            compteurBienPlaces += 1
        totalMalPlaces = t.count(i) - tableauEntree.count(i)
        if(compteurBienPlaces <= totalMalPlaces):
            tableauPlacement[1] += totalMalPlaces - compteurBienPlaces
            print(compteurBienPlaces, " ", tableauPlacement[0])
    tableauPlacement[0] += compteurBienPlaces
    print(compteurBienPlaces, " ", tableauPlacement[0])
        






def jeu():
    compteur = 0
    reponse = "";
    choix_ordinateur()
    print("la reponse est: ", t, " comme ca plus utile pour faire des tests")
    while(compteur <12):
        compteur += 1
        choix_utilisateur()
        placement()
        if(tableauPlacement == [4, 0]):
            print("GG ! 4 corrects et 0 mal placés")
            return True
        elif(tableauPlacement[0] == 0):
            print("aucun nombre bien placé", end =" ")
        elif(tableauPlacement[0] == 1):
            print("Un nombre bien placé", end = " ")
        else:
            print(tableauPlacement[0], " nombres bien placés", end = " ")
        if(tableauPlacement[1] == 0):
            print("et aucun mal placé")
        elif(tableauPlacement[1] == 1):
            print("et un nombre mal placé")
        else:
            print("et ", tableauPlacement[1], " nombres bien placés")
    return False
while(joue):
    if(jeu() == False):
        print("Perdu !")
    reponse = input("Voulez vous rejouer ? o/n")
    if (reponse == "n"):
        joue = False;
So I think everything is ok in this code but the "Placement" function, however I can't manage to find it.
Could you help me find how to count correctly ?
Thanks for any help you could bring !


Edit: I'm sorry if you can't understand my code because of the lack of comments, feel free to ask me if there's anything you don't get
Reply
#2
If the answer is 1234 and the user enters 5115, how many misplaced numbers are there? one or two? Same question for 1134 and 5551
Reply
#3
(Feb-03-2018, 11:59 AM)Gribouillis Wrote: If the answer is 1234 and the user enters 5115, how many misplaced numbers are there? one or two? Same question for 1134 and 5551

for 1234 and 5115, both 1's are misplaced, the 1 is also misplaced for 1134 and 5551
if the answer is 2332 and the user types 2232 there would be 3 good answers and 0 misplaced number because every 2's needed in the answer are well placed
Reply
#4
If you replace placement() with this, it seems to be working
def placement():
    paires = list(zip(t, tableauEntree))
    n = len(paires)
    paires = [(u, v) for u, v in paires if u != v]
    compteurBienPlaces = n - len(paires)
    if paires:
        a, b = zip(*paires)
        compteurMalPlaces = sum(1 for x in b if x in a)
    else:
        compteurMalPlaces = 0
    tableauPlacement[:] = [compteurBienPlaces, compteurMalPlaces]
In your code at line 28, you need tableauPlacement[:] = [0, 0] because
if you write tableauPlacement = [0, 0], this variable becomes a local variable and the global tableauPlacement is not changed, but there are other errors.

At line 70, you need 'mal' instead of 'bien'
Reply
#5
Thank you for your answer !
For the "bien " and "mal", I corrected the error right after I posted here, I had tried a few more things without results

for TableauPlacement, it is because I "declared" the variable accidentaly ?
i would have never guessed.

So in the code, you are creating a sort of dictionnary, then line 4 it's an abridged version of a "for " condition, but I don't get why there is (u, v) before this,
This line also seems to exclude every "group" of numbers where numbers aren't identical,
then you're counting every pair where numbers are the same,


then I have trouble with that part:
    if paires:
        a, b = zip(*paires)
        compteurMalPlaces = sum(1 for x in b if x in a)
    else:
        compteurMalPlaces = 0
what I understand is:
if the "paires" list has some varialbes in it then new a and b lists are equal to every number in "paires"
then for each variable in b, if the variable exists in a, then you add 1 to a counter ?


that means first, you separate the numbers in two groups; those who meet the condition I set and the others,
and then you check with the others if they are just misplaced


wow that's clever, I never thought of separating my array in groups !
Reply
#6
Here is an independent script with prints to show what's going on
t = [1, 2, 3, 4]
tableauEntree = [5, 1, 1, 4]
tableauPlacement = [0, 0]

def placement():
    print('t:', t)
    print('tableauEntree:', tableauEntree)
    paires = list(zip(t, tableauEntree))
    print('paires (1):', paires)
    n = len(paires)
    paires = [(u, v) for u, v in paires if u != v]
    print('paires (2):', paires)
    compteurBienPlaces = n - len(paires)
    print('bien places: {} = {} - {}'.format(compteurBienPlaces, n, len(paires)))
    if paires:
        a, b = zip(*paires)
        print('a:', a)
        print('b:', b)
        compteurMalPlaces = sum(1 for x in b if x in a)
    else:
        compteurMalPlaces = 0
    print('mal places:', compteurMalPlaces)
    tableauPlacement[:] = [compteurBienPlaces, compteurMalPlaces]
    
placement()
The result is this
Output:
t: [1, 2, 3, 4] tableauEntree: [5, 1, 1, 4] paires (1): [(1, 5), (2, 1), (3, 1), (4, 4)] paires (2): [(1, 5), (2, 1), (3, 1)] bien places: 1 = 4 - 3 a: (1, 2, 3) b: (5, 1, 1) mal places: 2
The first zip groups corresponding numbers in t and tableauEntree. See the paires (1) print. Then well placed pairs are removed from the list. It remains only the pairs that don't match (paires (2)). The second zip separates the pairs again, see lists a and b above. It remains the slots where the computer's choice and the player's choice don't match. Then we sum 1 for every number in the player's list that appears in the computer's list. This is the count of misplaced numbers.
(Feb-03-2018, 02:00 PM)Staren Wrote: for TableauPlacement, it is because I "declared" the variable accidentaly ?
Indeed there is no formal variable declaration in python but a variable becomes a local variable in a function if it is on the left hand side of an assignment statement. So a statement foo = 3 in a function's body declares foo as a local variable, but foo[1] = 3 doesn't, nor does x = foo.
Reply
#7
I see, I can understand everything now
Thanks again for your help !
I hope you have a nice day, too !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help (mastermind game) sseansssean 2 2,909 Jul-06-2020, 12:47 PM
Last Post: deanhystad
  Mastermind Davidlit95 2 3,384 Oct-16-2017, 10:17 PM
Last Post: Davidlit95

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020