Reputation: 221
For a project of mine, I have to do a tic-tac-toe solver, and I would like to just ask for some help optimizing some code.
Task: Depending on the winner( x or o) , return the appropriate result
How I did It: I checked Horizontal, vertical, and diagonal strategies for the result
What I need help with : I am mostly repeating the same code, but different if statement for each case, and I am just wondering if there is a more universal method to do this.
Current Code: (Diagonal win)
if diagcounter==size and (board[0][0]=="x") :
print("Win Diagonally")
return "X has won"
elif diagcounter==size and (board[0][0]=="o"):
print("Win Diagonally")
Horizontal win:
if vertcounter==size and board[0][x]=="x":
print("Win vertically")
return "X has won"
elif vertcounter==size and board[0][x]=="o":
print("Win vertically")
return "O has won"
As you can see, they are almost the same, but since I need to check the letter at the spot, I don`t know how to optimize it.
Upvotes: 2
Views: 677
Reputation: 1217
You could create a function to handle "winning" and have your if statements call that.
def win(method, team):
print("Win "+method)
return team+" has won"
if diagcounter==size and (board[0][0]=="x") :
return(win("diagonally", "x"))
elif diagcounter==size and (board[0][0]=="o"):
return(win("diagonally", "o"))
if vertcounter==size and board[0][x]=="x":
return(win("vertically", "x"))
elif vertcounter==size and board[0][x]=="o":
return(win("vertically", "o"))
Upvotes: 0
Reputation: 293
You could hold a list of the indices for each row/column/diagonal. So for example, the first row should be sequence_indices = [(0, 0), (0, 1), (0, 2)]
. The main diagonal should be sequence_indices = [(0, 0), (1, 1), (2, 2)]
.
Now whenever you write in your code vertcounter
or diagcounter
use a function counter(sequence_indices)
, and instead of board[0][x]
or board[0][0]
, use
first_i, first_j = sequence_indices[0]
board[first_i][first_j]
Another way to optimize this is to use board like so:
If a cell contains x
, then board
in that cell should hold the number 1
. If the cell contains o
, board
in that cell should hold the number -1
, and if the cell is empty it should be 0
.
Now to calculate rowcounter
or whatever-counter just sum over these cells and compare them to +size
(x
wins), or to -size
(o
wins).
Upvotes: 2