Home > Net >  Mastermind game compare lists Python
Mastermind game compare lists Python

Time:09-04

I've start to create a mastermind boardgame in python as a first project. I'm a beginner.

The code is far from perfect but it's working, except one part. The list comparing. First try:

    if gs.board[actual_line] == gs.ai_choice[0]:
        print("You WIN")
    else:
        
        hit = [i for i, j in zip(gs.board[actual_line], gs.ai_choice[0]) if i == j]
        hit = len(hit)
        re_mylist = [i for i, j in zip(gs.board[actual_line], gs.ai_choice[0]) if i != j]
        re_ailist = [i for i, j in zip(gs.ai_choice[0], gs.board[actual_line]) if i != j]

        for idx, x in enumerate(re_mylist):
            for idy, y in enumerate(re_ailist):
                if x == y:
                    common.append((idy, y))

        print(f"hit: {hit}")
        white = len(set(common))
        print(f"white: {white}")

With this two lists:

list_1 = ["orange", "orange", "green", "red"]

list_2 = ["orange", "red", "orange", "green"]

I'd like to see 1 hit and 3 almost But the truth is : 2 hit 2 almos

I googled a lot. Tried lots of other's mastermind game but all of them work differently..

import random
import collections

length = 4
# pattern = [random.choice('abcdef') for _ in range(length)]
pattern = ['a', 'b', 'a', 'c']
print(*pattern)
counted = collections.Counter(pattern)

def running():
    guess = input('?: ')
    guess_count = collections.Counter(guess)
    close = sum(min(counted[k], guess_count[k]) for k in counted)
    exact = sum(a == b for a, b in zip(pattern, guess))
    close -= exact
    print('Exact: {}. Close: {}.'.format(exact, close))
    return exact != length


while running():
    pass

print('done!')

outcome:

a b a c

?: a a c d

Exact: 2. Close: 1.

Finally:

import random
from collections import Counter

choices = ["red", "green", "yellow", "blue", "orange", "purple"]

my_list = random.choices(choices, k=4)
ai_list = random.choices(choices, k=4)


def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return len(result)

dummy_my_list = [x for x in my_list]
dummy_ai_list = [x for x in ai_list]
r = 0
my_pop = []

for i in range(4):
    if my_list[i] == ai_list[i]:
        my_pop.append(int(i))
        r  = 1

ac=Counter(dummy_my_list)
bc=Counter(ai_list)
res=[]
pop = len(my_pop)

if pop > 0:
    for i in range(pop):
        dummy_my_list.pop(my_pop[i])
        dummy_ai_list.pop(my_pop[i])

for i in set(dummy_my_list).intersection(set(dummy_ai_list)):
    res.extend([i] * min(bc[i], ac[i]))

w = len(res)

print(f"hit: {r}")
print(f"almost: {w}")

I know it's a mess but its working 95% of times. However, sometimes it crashes due to

dummy_my_list.pop(my_pop[i])
IndexError: pop index out of range

I don't know how to proceed. Could somebody help me with this?

I would appreciate it.

CodePudding user response:

I think the issue is coming from how indexes are being managed.

If you create a list like this with five elements:

my_pop = [1, 2, 3, 4, 5]

You can check the length and find that it returns a result of 5:

pop = len(my_pop)
5

But when you iterate over things, the iteration starts from an index of zero.

for i in range(pop):
     print(i)

This will give you a response of 0, 1, 2, 3, 4.

If you tried to access the element at the fifth index of the list my_pop:

my_pop[5]

You will get an error. This is because there is no element in the fifth index of my_pop because the indexing starts from zero.

  • The integer value of 1 in my_pop is stored at the index position of 0.
  • The integer value of 5 in my_pop is stored at the index position of 4.

CodePudding user response:

it might be because your pop index is the length of the list from 1. You probably want it to be -1 as lists start from zero.

instead of pop = len(my_pop) try pop = len(my_pop) - 1

  • Related