Connect 4
unknown
python
a year ago
2.9 kB
3
Indexable
Never
import random import tkinter as tk # Define the board board = [[' '] * 7 for _ in range(6)] # Define the player colors player_colors = ['X', 'O'] # Define the current player current_player = 0 # Define the function to drop a piece def drop_piece(column): # Check if the column is valid if column < 0 or column >= 7: return False # Find the first empty row in the column for row in range(6): if board[row][column] == ' ': board[row][column] = player_colors[current_player] return True return False # Define the function to check for a winner def check_winner(): # Check for a winner in each row for row in range(6): for column in range(4): if board[row][column] == board[row][column + 1] == board[row][column + 2] == board[row][column + 3] != ' ': return board[row][column] # Check for a winner in each column for column in range(7): for row in range(3): if board[row][column] == board[row + 1][column] == board[row + 2][column] == board[row + 3][column] != ' ': return board[row][column] # Check for a winner in each diagonal for row in range(3): for column in range(4): if board[row][column] == board[row + 1][column + 1] == board[row + 2][column + 2] == board[row + 3][column + 3] != ' ': return board[row][column] for row in range(3): for column in range(3): if board[row][column] == board[row + 1][column + 1] == board[row + 2][column + 2] == board[row + 3][column + 3] != ' ': return board[row][column] # No winner return None # Define the function to print the board def print_board(): for row in board: print(' '.join(row)) # Create the main window window = tk.Tk() # Create the labels for the columns column_labels = [] for column in range(7): column_label = tk.Label(window, text=str(column)) column_label.grid(row=0, column=column) column_labels.append(column_label) # Create the buttons for the rows row_buttons = [] for row in range(6): row_buttons.append([]) for column in range(7): button = tk.Button(window, text=' ', command=lambda column=column: drop_piece(column)) button.grid(row=row + 1, column=column) row_buttons[row].append(button) # Create the label for the current player current_player_label = tk.Label(window, text='Current Player: {}'.format(player_colors[current_player])) current_player_label.grid(row=7, column=0, columnspan=7) # Create the button to start a new game start_new_game_button = tk.Button(window, text='Start New Game', command=start_new_game) start_new_game_button.grid(row=8, column=0, columnspan=7) # Start the game while True: # Get the player's move column = int(input('Enter your move (0-6): ')) # Drop the piece if drop_piece(column): # Check for a winner winner = check_winner() if winner is not None: print('Player {} wins!'.format(winner)) break