Jun-30-2020, 10:06 PM
(This post was last modified: Jun-30-2020, 10:07 PM by blacklight.)
Hi so for my AI class intro we had to programme a game. I made tic tac toe in python. If you look at the check_for_tie function, it looks a little bit too long and janky. Is there a way to simplify it?
#creating tic tac toe # 1 create a board # 2 print the board # 3 create a function that asks the users for input. # 4 create a function that checks for a win. # global variable game = True #create a board board = [ "-", "-", "-", "-", "-", "-", "-", "-", "-", ] player_won = "none" # create a function that prints the board def print_board(): print("|" + board[0] + "|" + board[1] + "|" + board[2] + "|") print("|" + board[3] + "|" + board[4] + "|" + board[5] + "|") print("|" + board[6] + "|" + board[7] + "|" + board[8] + "|") # create the functions that ask the two users for input. You wil have an x and an o # we want it to ask for the position def player_x(): position = input("Choose your position from 1-9: ") position = int(position) - 1 board[position] = "x" # the function for player o def player_o(): position = input("Choose your position from 1-9: ") position = int(position) - 1 board[position] = "o" tie = False # check for rows def check_rows(): global game row1 = board[0] == board[1] == board[2] != "-" row2 = board[3] == board[4] == board[5] != "-" row3 = board[6] == board[7] == board[8] != "-" if row1 or row2 or row3: game = False if row1: print("You have won, player: " + board[0]) elif row2: print("You have won, player: " + board[3]) elif row3: print("You have won, player: " + board[6]) # check for diagonals def check_diagonals(): global game diag1 = board[2] == board[4] == board[6] != "-" diag2 = board[0] == board[4] == board[8] != "-" if diag1 or diag2: game = False if diag1: return print("You have won, player: " + board[2]) elif diag2: return print("You have won, player: " + board[0]) # check for columns def check_columns(): global game c1 = board[0] == board[3] == board[6] != "-" c2 = board[1] == board[4] == board[7] != "-" c3 = board[2] == board[5] == board[8] != "-" if c1 or c2 or c3: game = False if c1: return print("You have won, player: " + board[0]) if c2: return print("You have won, player: " + board[1]) if c3: return print("You have won, player: " + board[2]) # create a function where all the positions are filled in with x's or o's. So basically where everything doesn't equal "-". def check_for_tie(): global game b1 = board[0] and board[1] and board[2] and board[3] and board[4] and board[5] and board[6] and board[7] and board[8] != "-" if b1: game = False print("You have tied!") # creating the check function def check_for_winner(): check_rows() check_diagonals() check_columns() # creating the game loop # this is the game loop that makes the code run while game: print_board() player_x() check_for_winner() print_board() player_o() check_for_winner() check_for_tie()