tic tac toe - How to improve a code for Tic Tac Toe-Check Victory in Python -
i writing python code making tic tac toe game. need write function takes in 3 inputs, board, x, , y. board being current display of board , x , y being values of 0, 1, or 2. game set ask user coordinates.
def checkvictory(board, x, y): #check if previous move on vertical line , caused win if board[0][y] == ('x') , board[1][y] == ('x') , board [2][y] == ('x'): return true if board[0][y] == ('o') , board[1][y] == ('o') , board [2][y] == ('o'): return true #check if previous move on horizontal line , caused win if board[x][0] == ('x') , board[x][1] == ('x') , board [x][2] == ('x'): return true if board[x][0] == ('o') , board[x][1] == ('o') , board [x][2] == ('o'): return true #check if previous move on main diagonal , caused win if board[0][0] == ('x') , board[1][1] == ('x') , board [2][2] == ('x'): return true if board[0][0] == ('o') , board[1][1] == ('o') , board [2][2] == ('o'): return true #check if previous move on secondary diagonal , caused win if board[0][2] == ('x') , board[1][1] == ('x') , board [2][0] == ('x'): return true if board[0][2] == ('o') , board[1][1] == ('o') , board [2][0] == ('o'): return true return false #end of checkvictory function
the function called in game loop so
p_x, p_y = playerturn(board) #let player take turn displayboard(board) #show board after move has been made if checkvictory(board, p_x, p_y): #see if user has won print("congratulations, win!") newgame(board) #game on start new 1 continue
and it's similar computer turn
i feel there better way write function. feel should using x , y more or there better way check rather writing possibilities. what's better way write this? make short , concise.
i can't see why need x
, y
parameters, you're supposed check if there 3 x letters or 3 o letters in row, don't need coordinates that. instead edit board first updates coordinates player entered, check if victory happened.
here's how it, if want use method - feel free to. can still learn version.
def check_victory(board): combinations = [ # horizontal ((0,0), (1,0), (2,0)), ((0,1), (1,1), (2,1)), ((0,2), (1,2), (2,2)), # vertical ((0,0), (0,1), (0,2)), ((1,0), (1,1), (1,2)), ((2,0), (2,1), (2,2)), # crossed ((0,0), (1,1), (2,2)), ((2,0), (1,1), (0,2)) ] coordinates in combinations: letters = [board[y][x] x,y in coordinates] if len(set(letters)) == 1: return letters[0] # returns corresponding letter winner (x/o) return false
notice uses list comprehension , sets. if you're not familiar those, recommend learn them before using solution.
Comments
Post a Comment