ag3

mail@pastecode.io avatar
unknown
python
2 months ago
4.6 kB
4
Indexable
Never
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Artificial Intelligence Lab Skills
Assignment 3 Connect Four

Author(s): 
Group: 
Contributor(s): 
Average hours spent per person: 
"""

import random


class Player:
    def __init__(self, symbol, name):
        self.symbol = symbol
        self.name = name

    def get_move(self, board):
        if self.name == "Random Computer Player":
            valid_moves = [c for c in range(len(board[0])) if board[0][c] == ' ']
            return random.choice(valid_moves)
        else:
            while True:
                try:
                    column = int(input(f"{self.name} ({self.symbol}), enter your move (0-{len(board[0]) - 1}): "))
                    if 0 <= column < len(board[0]) and board[0][column] == ' ':
                        return column
                    else:
                        print("Column is full or out of bounds, try again.")
                except ValueError:
                    print("Invalid input, please enter a number.")


class Board:
    def __init__(self, rows=6, columns=7):
        self.rows = rows
        self.columns = columns
        self.board = [[' ' for _ in range(columns)] for _ in range(rows)]

    def print_board(self):
        for row in self.board:
            print('|' + '|'.join(row) + '|')

    def make_move(self, column, symbol):
        for row in reversed(range(self.rows)):
            if self.board[row][column] == ' ':
                self.board[row][column] = symbol
                return True
        return False

    def check_winner(self, symbol):
        # horizontal locations
        for column in range(self.columns - 3):
            for row in range(self.rows):
                if self.board[row][column] == symbol and self.board[row][column + 1] == symbol and \
                        self.board[row][column + 2] == symbol and self.board[row][column + 3] == symbol:
                    return True

        # vertical locations
        for column in range(self.columns):
            for row in range(self.rows - 3):
                if self.board[row][column] == symbol and self.board[row + 1][column] == symbol and \
                        self.board[row + 2][column] == symbol and self.board[row + 3][column] == symbol:
                    return True

        # positively sloped diagonals
        for column in range(self.columns - 3):
            for row in range(self.rows - 3):
                if self.board[row][column] == symbol and self.board[row + 1][column + 1] == symbol and \
                        self.board[row + 2][column + 2] == symbol and self.board[row + 3][column + 3] == symbol:
                    return True

        # negatively sloped diagonals
        for column in range(self.columns - 3):
            for row in range(3, self.rows):
                if self.board[row][column] == symbol and self.board[row - 1][column + 1] == symbol and \
                        self.board[row - 2][column + 2] == symbol and self.board[row - 3][column + 3] == symbol:
                    return True

        return False

    def is_full(self):
        return all(self.board[row][0] != ' ' for row in range(self.rows))


def play_game():
    board = Board()
    player1_name = input("Enter your name: ")
    player1 = Player('X', player1_name)
    player2 = Player('O', "Random Computer Player")
    current_player = player1

    while True:
        board.print_board()
        if current_player.name == "Random Computer Player":
            column = current_player.get_move(board.board)
            print(f"Random Computer Player's turn. Chooses column: {column}")
        else:
            try:
                column = int(input(f"{current_player.name}'s turn. Choose column (0-6): "))
                if not 0 <= column <= 6:
                    raise ValueError
            except ValueError:
                print("Please enter a valid column number.")
                continue

        if board.make_move(column, current_player.symbol):
            if board.check_winner(current_player.symbol):
                board.print_board()
                print(f"{current_player.name} wins!")
                break
            elif board.is_full():
                board.print_board()
                print("Draw!")
                break
            current_player = player1 if current_player == player2 else player2
        else:
            print("This column is full. Please choose a different one.")


if __name__ == '__main__':
    play_game()
Leave a Comment