#๐Ÿ”’ win checker tictactoe

110 messages ยท Page 1 of 1 (latest)

mighty goblet
#

Still struggling to make a win checkincident_actioned

rose shoalBOT
#

@mighty goblet

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

mighty goblet
#

this is the code

#

im trying to run a def

bold chasm
#

in 3x3 you basically only have 6 lines to check for victory

#

rows and columns and the 2 diagonals (3+3+2)

#

maybe make a function to get all the lines, columns and diagonals and then you check if one of them is full of Xs or Os

mighty goblet
#

but that is very long

#
  • when i do it it doesnt work
#
tries = [1,2,3,4,5,6,7,8,9]  

other_choices = []
win_points = 1600
lose_points = -200
draw_points = 800

player1 = str(input("choose the name of player1"''))  
player2 = str(input("choose the name of player2"''))  

won_games = 0
lost_games = 0
drawn_games = 0

PIECE_X = "X"  
PIECE_O = "O"

pieces = [PIECE_X, PIECE_O]  



print("player1 is", player1)  
print("player2 is", player2)  

def check_winner(board):
    if board[0][0] == board ==[0][1] == board[0][2] == PIECE_X:
        print(player1,"omg u won")
        exit()

    ...

def get_user_choice():
    while True:
        try:
          choice = int(input("player please choose a number between 0-8"))
          if 0 <= choice <=8 :
              return choice
        except ValueError:  
            print("invalid input try again")


def main():  
    current_turn = 1

    board = [["0", "1 ","2"],
         ["3", "4", "5"],
         ["6", "7", "8"]]
    
    players = [player1, player2]  # PEP8
    print(*players, "welcome to tic tac TOE!")  
    while True:        
        choice = get_user_choice()
        if choice in other_choices:
            print("please choose another number")  # Harsh, you could improve this.
            continue
        else:
            current_turn = current_turn+1
            other_choices.append(choice)
        if current_turn %2 == 0:
            print(player2, "turn")
            played_piece = PIECE_O
        else:
            print(player1, "turn")
            played_piece = PIECE_X

        row, column = divmod(choice, 3)  # Look into this!
        board[row][column] = played_piece
        for row in board:  
            print(row)

        if check_winner(board):
            print(played_piece, "wins") 

        if current_turn == 10:
            print("Draw!")  
            break


if __name__ == "__main__":  # Look into this!
    main()
prime harness
#

How i did it when i made tic tac toe was to sum the caracters into lines and see if it equals the caracter_that_last_stepped*3

#

For u its

any([
b[0]=="O"*3,
b[1]=="O"*3,
b[2]=="O"*3,

b[0][0]+b[1][0]+b[2][0]=="O"*3,
b[0][1]+b[1][1]+b[2][1]=="O"*3,
b[0][2]+b[1][2]+b[2][2]=="O"*3,

b[0][0]+b[1][1]+b[2][2]=="O"*3,
b[0][2]+b[1][1]+b[2][0]=="O"*3
])
#

b stands for board
and "O" stands for the guy that last stepped

civic frost
#

i think creating a win checker for tictactoe is actually one of the hardest task in computer science.

bold chasm
#

except maybe creating a humanoid robot

civic frost
#

when you think about it, a win checker for tictactoe is just a big pile of edge cases. you cannot simplify it.

bold chasm
#
    def __check_victory(self):
        for row in self.grid:
            for i in range(len(row) - self.alignment_length + 1):
                if np.all(row[i:i + self.alignment_length] == self.turn):
                    return True
        for column in self.grid.T:
            for i in range(len(column) - self.alignment_length + 1):
                if np.all(column[i:i + self.alignment_length] == self.turn):
                    return True
        for diagonal in self.__get_diagonals():
            for i in range(len(diagonal) - self.alignment_length + 1):
                if np.all(diagonal[i:i + self.alignment_length] == self.turn):
                    return True
        return False

I use that for a x,y sized tictactoe

civic frost
#

you can simplify it if you know the position of the latest piece.

bold chasm
#

yes didnt think of it before

#

thats smart actually

civic frost
#

i made a n-dimensional one. there it's very important to be efficient.

prime harness
civic frost
#

it takes the size of the board as a tuple, also the number of pieces to win, and the number of players.

prime harness
civic frost
#

maybe.

bold chasm
#

did u do with raw python

civic frost
#

i did everything with raw python. using a dict as the board.

bold chasm
#

ow okay

civic frost
#

you could try to find clever tricks to make it look more interesting. but probably it just makes it harder to read and error-prone.

won = [played_piece] * 3 in (
    board[row],
    list(tuple(zip(*board))[col]),
    [board[i][i] for i in range(3)],
    [board[i][2-i] for i in range(3)],
)```
mighty goblet
#

hi uhm

#

how can i implment these things in my code

#

like if i want it in a define or something

civic frost
#

currently you have py if check_winner(board): print(played_piece, "wins")
and ```py
def check_winner(board):
if board[0][0] == board ==[0][1] == board[0][2] == PIECE_X:
print(player1,"omg u won")
exit()

...```
mighty goblet
#

yup

civic frost
#

now if you wanted to access the row, col, and played_piece in check_winner, then you would have to add them as additional parameters.
but played_piece is the same as board[row][col].

mighty goblet
#

i get mixed up in parameters

#

sometimes

#

played piece = x or o

civic frost
#

so you could pass all the values like ```py
if check_winner(board, row, col):
print(played_piece, "wins")

def check_winner(board, row, col):
played_piece = board[row][col]```

mighty goblet
#

seems solid !

mighty goblet
#

or the other long one

civic frost
#

or the even longer one ```py
any(
played_piece == board[0][0] == board[0][1] == board[0][2],
played_piece == board[1][0] == board[1][1] == board[1][2],
played_piece == board[2][0] == board[2][1] == board[2][2],

played_piece == board[0][0] == board[1][0] == board[2][0],
played_piece == board[0][1] == board[1][1] == board[2][1],
played_piece == board[0][2] == board[1][2] == board[2][2],

played_piece == board[0][0] == board[1][1] == board[2][2],
played_piece == board[0][2] == board[1][1] == board[2][0],

)```

#

or ```py
(played_piece,) * 3 in (
(board[0][0], board[0][1], board[0][2]),
(board[1][0], board[1][1], board[1][2]),
(board[2][0], board[2][1], board[2][2]),

(board[0][0], board[1][0], board[2][0]),
(board[0][1], board[1][1], board[2][1]),
(board[0][2], board[1][2], board[2][2]),

(board[0][0], board[1][1], board[2][2]),
(board[0][2], board[1][1], board[2][0]),

)```

#

i think it looks very tidy.

mighty goblet
#

yup

#

if check_winner(board, row, column):
^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'check_winner' where it is not associated with a value

#

but how?

civic frost
#

did you assign a value to check_winner?

#

or did you define the function after calling main()?

mighty goblet
#

i defined it in the main itself

civic frost
#

you cannot call the function before defining it.

mighty goblet
#

before running main()

civic frost
#

when you define check_winner within main, you still have to define it before using it.

mighty goblet
#

one sec

mighty goblet
#

i dont understand

civic frost
#

def check_winner(): ... is basically like assigning a value to the variable check_winner

#

you cannot use variables before assigning a value to them.

#

you don't have to define it twice.

mighty goblet
#

ooooh ok

civic frost
#

this will result in an error: ```py
check_winner()

def check_winner():
...but this works fine:py
def check_winner():
...

check_winner()```

mighty goblet
#

@civic frost btw thanks for your help

#

i really appreciate

#

it

civic frost
#

i hope it helps. lemon_sweat

mighty goblet
#

?

mighty goblet
#

so i can make it print something

#

or do anything

civic frost
#

yes. i'm not sure what the function is supposed to do. but if the check is all then you can also just return the value without if.

#

i think the print is already in main.

mighty goblet
#

every time i make a move it prints the win print out

#

i can share my code if u want

#

!paste

rose shoalBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

civic frost
#

yes, i can't imagine why that happens.

mighty goblet
civic frost
#
        def check_winner():
           (played_piece,) * 3 in (
    (board[0][0], board[0][1], board[0][2]),
    (board[1][0], board[1][1], board[1][2]),
    (board[2][0], board[2][1], board[2][2]),

    (board[0][0], board[1][0], board[2][0]),
    (board[0][1], board[1][1], board[2][1]),
    (board[0][2], board[1][2], board[2][2]),
    
    (board[0][0], board[1][1], board[2][2]),
    (board[0][2], board[1][1], board[2][0]),
    print("YOU WON",player1)
)
#

yes, that's not correct.

mighty goblet
#

im rethinking my life choices

civic frost
#

you added the print into the check. you need an if. but i thought you had it in main.

mighty goblet
#

when i add the if it makes an error

civic frost
#

i think you would either just return a value, and then print in main```py
def check_winner(board, played_piece):
return (played_piece,) * 3 in (
...
)

if check_winner(board, played_piece):
print("YOU WON", played_piece)```
or directly print in check_winner

def check_winner(board, played_piece):
    if (played_piece,) * 3 in (
        ...
    ):
        print("YOU WON", played_piece)
)

check_winner(board, played_piece)```
#

if the function is in main, you can omit the parameters.

#
def check_winner():
    if (played_piece,) * 3 in (
        ...
    ):
        print("YOU WON", played_piece)
)

check_winner()```
mighty goblet
#

see \

civic frost
#

i just don't see why you would put the function into the main function.

#

it's nice to have small function. and check_winner is pretty big already.

mighty goblet
#

it very late for me

civic frost
#

okay

mighty goblet
#

oh

#

it worked

#

finnaly

#

im very tired

#

@civic frost thank you very much

#

maybe im tried thats why i did these dumb things lol

civic frost
#

good night lemon_sweat

mighty goblet
mighty goblet
#

!close

rose shoalBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.