Jeroen
Jeroen

Reputation: 105

Check if two out of three equal something

For a school project, I'm working on a TicTacToe game in python with an AI. Now i'm kinda stuck for a while. So i use this code to check if there is a winner:

playField = [['.','.','.'],['.','.','.'],['.','.','.']]
def checkWinner(L):
    return ((playField[0][0] == L and playField[0][1] == L and playField[0][2] == L) or #Line 1 horizontal
        (playField[1][0] == L and playField[1][1] == L and playField[1][2] == L) or #Line 2 horizontal
        (playField[2][0] == L and playField[2][1] == L and playField[2][2] == L) or #Line 3 horizontal
        (playField[0][0] == L and playField[1][0] == L and playField[2][0] == L) or #Colomn a vertical
        (playField[0][1] == L and playField[1][1] == L and playField[2][2] == L) or #Colomn b vertical
        (playField[0][2] == L and playField[1][2] == L and playField[2][2] == L) or #Colomn c vertical
        (playField[0][0] == L and playField[1][1] == L and playField[2][2] == L) or #Diagonal left-top to right-bot
        (playField[0][2] == L and playField[1][1] == L and playField[2][0] == L)) #Diagonal right-top to left-bot

And this is working great, but for my ai i want to check if either he has two on a row or the 'enemy' has two in a row. So basically i want to check if two out of three equal 'L' and I have no clue on how to rewrite the function do that, or another way to check if two out of three equal 'L'.

Help would be great!

Greetings, Jeroen

Upvotes: 1

Views: 813

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

The rows of the board are

[playField[i] for i in range(3)]

The columns of the board are

[[playField[i][j] for i in range(3)] for j in range(3)]

The diagonals are

[playField[i][i] for i in range(3)]

and

[playField[2-i][i] for i in range(3)] (thanks, @volcano!)

So you now are dealing with lists of threes (or lists of lists of threes).


Suppose you have a list such as

a = [10, 20, 10]

Then

sum(e == 10 for e in a)

Returns the number of items equals to 10. If this number is 2, then

sorted(enumerate(a), key=lambda (_, e): e == 10)[0][0]

will give the index of the (single) item that is not 10.


I think those are all of the building blocks you need.

Upvotes: 2

BingsF
BingsF

Reputation: 1329

Given a list foo = ['A', 'B', 'L', 'L'], you can check the number of 'L's with foo.count('L').

Upvotes: 1

Related Questions