2

I have made the main-game mechanics for the TicTacToe game; however, I don't know a way to code the end-game win conditions, i.e. How to find when someone wins/ties.

I tried using the all() function, but either this did not work, or I used it incorrectly (probably the latter).

Here is the full code, and the list of variables for the code (as there are no comments):

def get_grid():
    r1 = ['-','-','-']
    r2 = ['-','-','-']
    r3 = ['-','-','-']
    return r1, r2, r3

def get_coords():
    x = 0
    y = 0
    while True:
        try:
            x = int(input("x coord : "))
            y = int(input("y coord : "))
        except ValueError:
            print("Must be an integer")
        if x < 0 or x > 3 or y < 0 or y > 3:
            print('Both values must be in the grid!')
        else:
            break
    return x, y

def pgrid(x, y, r1, r2, r3, player):
    rdict = {1:r1, 2:r2, 3:r3}
    if x != 0 and y != 0:
        while True:
            if rdict[y][x-1] == '-':
                rdict[y][x-1] = player
                break
            else:
                print("Invalid Space!")
                x, y = get_coords()
    print('\t1\t2\t3')
    print('  1 |', end = '\t')
    for i in r1:
        print(i, end = '   |   ')
    print()
    print('  2 |', end = '\t')
    for i in r2:
        print(i, end = '   |   ')
    print()
    print('  3 |', end = '\t')
    for i in r3:
        print(i, end = '   |   ')
    print()


def main():
    r1, r2, r3 = get_grid()
    players = ['X', 'O']
    pgrid(0, 0, r1, r2, r3, None)
    win = False
    while win == False:
        for i in players:
            x, y = get_coords()
            pgrid(x, y ,r1 ,r2 , r3, i)

Variables
r1, r2 and r3 are the first, second, and third rows for the board. List
x and y are the coordinates where the 'X' or 'O' is placed. Integer
rdict navigates between the y value entered and the row of the board. Dictionary
player is the player. String players is a List of the players ('X' and 'O')
win is true when a player has won / the game has tied. Boolean

The win variable is what needs to change in answers to this question, I just need the code or at least an idea on how to code it (because I don't have any!).
Thanks in advance!

AJ123
  • 194
  • 2
  • 14

2 Answers2

1

What's the simplest way to check if three of the same letters are in a row or column? For the first column take r1[0], r2[0] and r3[0] and check if they all contain the same letter:

if r1[0] == 'X' and r2[0] == 'X' and r3[0] == 'X':
    print('First column meets victory conditions', 'X')

Now it would be a bit cumbersome to do this for all rows and columns and both letters, but fortunately we can just let some for loops do the work for us.

for letter in 'XO':
    for i in range(3):
        if r1[i] == letter and r2[i] == letter and r3[i] == letter:
            print('Column', i, letter)

For the rows just iterate over (r1, r2, r3) instead of the range(3) and check:

if row[0] == letter and row[1] == letter ...

And of course you can also use the all function and a list comprehension or generator expression to see if all letters are equal.

for row in (r1, r2, r3):
    if all(item == letter for item in row):
skrx
  • 19,980
  • 5
  • 34
  • 48
0

You can try my function :

def check_who_won(board):
 for letter in 'xo':
    if all(col == letter for row in board for col in row):
        return True
    for col in range(3):
        if all(board[row, col] == letter for row in range(3)):
            return True
    if (board[2, 0] and board[1, 1] and board[0, 2]) in letter:
        return True
    if all(board[index, index] == letter for index in range(3)):
        return True
return False
Dvir
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 11 '22 at 03:28
  • Welcome to SO. Thank you for your contribution. Exact code, as you included, meets the requirement to be an Answer (comments in contrast can simply be suggestions on what to try). That said, Code only answers are discouraged on SO, as raw code alone doesn't help future visitors learn what the issue is or how to solve similar issues in their own code. Consider editing to add an explanation or supporting docs. "Good" answers tend to receive more upvotes, too, as more people are helped by them over time. Looking forward to your future contributions & insights. – SherylHohman Jan 16 '22 at 19:12