import os
import random
def clear_screen():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
def create_board(rows, cols):
return [[' ' for _ in range(cols)] for _ in range(rows)]
def print_board(board):
for row in board:
print('|'.join(row))
print('-' * (len(row) * 2 - 1))
print(' '.join(str(i) for i in range(len(board[0]))))
def is_valid_move(board, col):
return board[0][col] == ' '
def drop_piece(board, col, player):
for row in range(len(board) - 1, -1, -1):
if board[row][col] == ' ':
board[row][col] = player
return True
return False
def check_winner(board, player):
# Check horizontally
for row in board:
for col in range(len(row) - 3):
if all(cell == player for cell in row[col:col+4]):
return True
# Check vertically
for col in range(len(board[0])):
for row in range(len(board) - 3):
if all(board[row+i][col] == player for i in range(4)):
return True
# Check diagonally (top-left to bottom-right)
for row in range(len(board) - 3):
for col in range(len(board[0]) - 3):
if all(board[row+i][col+i] == player for i in range(4)):
return True
# Check diagonally (top-right to bottom-left)
for row in range(len(board) - 3):
for col in range(3, len(board[0])):
if all(board[row+i][col-i] == player for i in range(4)):
return True
return False
def make_ai_move(board):
while True:
col = random.randint(0, len(board[0]) - 1)
if is_valid_move(board, col):
return col
def main():
rows = 6
cols = 7
player_turn = 'X'
board = create_board(rows, cols)
while True:
clear_screen()
print_board(board)
if player_turn == 'X':
try:
col = int(input(f"Player {player_turn}, choose a column (0-{cols-1}): "))
if col < 0 or col >= cols:
raise ValueError()
except ValueError:
print("Invalid input. Please choose a valid column.")
continue
else:
col = make_ai_move(board)
print(f"AI (Player {player_turn}) chose column {col}")
if is_valid_move(board, col):
if drop_piece(board, col, player_turn):
if check_winner(board, player_turn):
clear_screen()
print_board(board)
if player_turn == 'X':
print("Player X wins!")
else:
print("Computer wins!")
break
elif all(cell != ' ' for cell in board[0]):
clear_screen()
print_board(board)
print("It's a draw!")
break
else:
player_turn = 'O' if player_turn == 'X' else 'X'
else:
print("Column is full. Choose another column.")
if __name__ == "__main__":
main()
[H[2J | | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
0 1 2 3 4 5 6
[H[2J | | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | |X| |
-------------
0 1 2 3 4 5 6
AI (Player O) chose column 3
[H[2J | | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | | | | |
-------------
| | |O|X| |
-------------
0 1 2 3 4 5 6