Hello, I am new to Python and started coding a tic-tac-toe game. When it comes to alternating between player turns, I couldn’t find a solution not to change the turn when the player enters his own number into a already occupied place filled with his same number.
I would really appreciate your feedbacks.
Here is my code:
import numpy as np
row_count = 3
col_count = 3
def create_board():
board = np.zeros((row_count, col_count))
return board
def is_valid_location(board, row, col):
return board[row][col] == 0
def drop_piece(board, row, col, piece):
board[row][col] = piece
def show_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
for c in range(col_count):
for r in range(row_count - 2):
if board[r][c] == piece and board[r + 1][c] == piece and board[r + 2][c] == piece:
return True
for c in range(col_count - 2):
for r in range(row_count):
if board[r][c] == piece and board[r][c + 1] == piece and board[r][c + 2] == piece:
return True
for c in range(col_count - 2):
for r in range(row_count - 2):
if board[r][c] == piece and board[r + 1][c + 1] == piece and board[r + 2][c + 2] == piece:
return True
for c in range(col_count - 2):
for r in range(2, row_count):
if board[r][c] == piece and board[r - 1][c + 1] == piece and board[r - 2][c + 2] == piece:
return True
board = create_board()
turn = 1
show_board(board)
running = True
while running:
if turn == 1:
row = int(input("Player 1 Select A Row (0-2): "))
col = int(input("Player 1 Select A Column (0-2): "))
if is_valid_location(board, row, col):
drop_piece(board, row, col, 1)
if winning_move(board, 1):
show_board(board)
print("Player 1 Won, Congrats!!")
break
show_board(board)
turn += 1
if turn == 2:
row = int(input("Player 2 Select A Row (0-2): "))
col = int(input("Player 2 Select A Column (0-2): "))
if is_valid_location(board, row, col):
drop_piece(board, row, col, 2)
if winning_move(board, 2):
show_board(board)
print("Player 2 Won, Congrats!!")
break
show_board(board)
turn -= 1