基于列表的井字棋(checkWin)验证器开发遇阻求助
Hey there! Let's get that checkWin module sorted out for your Tic Tac Toe game. Since you mentioned your implementation is a bit different from most examples, I’ve put together two options that work seamlessly with your existing row variables.
Option 1: Direct Check Using Your Existing Row Variables
This version skips converting to a 2D list and checks each win condition directly against your row1, row2, row3 variables—perfect if you want to stick close to your current setup:
def checkWin(): # Check all rows for a win if row1[0] != " " and row1[0] == row1[1] == row1[2]: return row1[0] if row2[0] != " " and row2[0] == row2[1] == row2[2]: return row2[0] if row3[0] != " " and row3[0] == row3[1] == row3[2]: return row3[0] # Check all columns for a win if row1[0] != " " and row1[0] == row2[0] == row3[0]: return row1[0] if row1[1] != " " and row1[1] == row2[1] == row3[1]: return row1[1] if row1[2] != " " and row1[2] == row2[2] == row3[2]: return row1[2] # Check both diagonals for a win if row1[0] != " " and row1[0] == row2[1] == row3[2]: return row1[0] if row1[2] != " " and row1[2] == row2[1] == row3[0]: return row1[2] # If no winner found, return None return None
How to Use It
After a player makes a move, call the function like this to check for a winner:
winner = checkWin() if winner: print(f"Player {winner} takes the win! 🎉") # Add game-over logic here else: # Continue the game loop print("No winner yet—keep playing!")
Option 2: Flexible Combination-Based Check
If you want a more scalable approach (great if you ever expand to larger boards later), this version uses coordinate combinations to check wins. It first wraps your rows into a 2D list for easier indexing:
def checkWin(): # Define all possible winning position combinations (row, column) winning_combinations = [ # Rows [(0,0), (0,1), (0,2)], [(1,0), (1,1), (1,2)], [(2,0), (2,1), (2,2)], # Columns [(0,0), (1,0), (2,0)], [(0,1), (1,1), (2,1)], [(0,2), (1,2), (2,2)], # Diagonals [(0,0), (1,1), (2,2)], [(0,2), (1,1), (2,0)] ] # Wrap your existing rows into a single 2D board list board = [row1, row2, row3] # Check each combination for a win for combo in winning_combinations: pos1 = board[combo[0][0]][combo[0][1]] pos2 = board[combo[1][0]][combo[1][1]] pos3 = board[combo[2][0]][combo[2][1]] if pos1 != " " and pos1 == pos2 == pos3: return pos1 # No winner found return None
This approach keeps your win conditions organized in one place, making it easy to tweak or add new combinations if needed.
Both options play nicely with your existing gameBoard() and checkPosition() functions—just drop whichever fits your style into your code!
内容的提问来源于stack exchange,提问作者Twissted

