Connect4 Game

How this game is playe can be found at here.

Python

ROWS = 6
COLS = 7

def create_board():
    return [[' ' for _ in range(COLS)] for _ in range(ROWS)]

def print_board(board):
    for row in board:
        print('|'.join(row))
    print('-' * (2 * COLS - 1))
    print(' '.join(map(str, range(COLS))))

def drop_token(board, col, token):
    for row in reversed(range(ROWS)):
        if board[row][col] == ' ':
            board[row][col] = token
            return row, col
    return None  # Column is full

def check_winner(board, row, col, token):
    def count_direction(dr, dc):
        r, c = row + dr, col + dc
        count = 0
        while 0 <= r < ROWS and 0 <= c < COLS and board[r][c] == token:
            count += 1
            r += dr
            c += dc
        return count

    directions = [ (0, 1), (1, 0), (1, 1), (1, -1) ]
    for dr, dc in directions:
        count = 1 + count_direction(dr, dc) + count_direction(-dr, -dc)
        if count >= 4:
            return True
    return False

if __name__ == "__main__":
    board = create_board()
    current_player = 0
    tokens = ['X', 'O']

    while True:
        print_board(board)
        
        while True:
            try:
                col = int(input(f"Player {current_player + 1} ({tokens[current_player]}), choose column (0-{COLS-1}): "))
                if col < 0 or col >= COLS:
                    print("Invalid column. Please choose a number between 0 and 6.")
                    continue
                result = drop_token(board, col, tokens[current_player])
                if result is None:
                    print(f"Column {col} is full. Try another one.")
                    continue
                else:
                    row, col = result
                    break
            except ValueError:
                print("Please enter a valid integer.")

        if check_winner(board, row, col, tokens[current_player]):
            print_board(board)
            print(f"Player {current_player + 1} ({tokens[current_player]}) wins!")
            break

        current_player = 1 - current_player

 

Java

  1 public class Connect4 {
  2     char[][] board = new char[6][7];
  3 
  4     public Connect4(char[][] board) {
  5         this.board = board;
  6     }
  7 
  8     public static void main(String[] args) {
  9         Connect4 game = new Connect4(new char[6][7]);
 10         game.fillBoard(' ');
 11         Scanner input = new Scanner(System.in);
 12         char player = 'X';
 13         while (true) {
 14             game.showGameBoard();
 15             System.out.print("Player " + player + ", please enter the column where you'd like to drop your piece: ");
 16             int col = input.nextInt();
 17             if (game.tryDropPiece(col, player)) {
 18                 if (game.checkForWin()) {
 19                     System.out.println("Player " + player + " wins!");
 20                     game.showGameBoard();
 21                     return;
 22                 }
 23                 player = game.switchPlayer(player); // Switch players
 24             }
 25         }
 26     }
 27 
 28     public char[][] fillBoard(char myChar) {
 29         for (int row = 0; row < board.length; row++) {
 30             Arrays.fill(board[row], 0, board[row].length, myChar);
 31         }
 32         return board;
 33     }
 34 
 35     public void showGameBoard() {
 36         System.out.println();
 37         for (int row = 0; row < board.length; row++) {
 38             System.out.print("|");
 39             for (int col = 0; col < board[row].length; col++) {
 40                 System.out.print(" " + board[row][col] + " |");
 41             }
 42             System.out.println();
 43         }
 44     }
 45 
 46     public boolean tryDropPiece(int col, char player) {
 47         if (board[0][col] != ' ') {
 48             System.out.println("That column is already full.");
 49             return false;
 50         }
 51         for (int row = board.length - 1; row >= 0; row--) {
 52             if (board[row][col] == ' ') {
 53                 board[row][col] = player;
 54                 return true;
 55             }
 56         }
 57         return false;
 58     }
 59 
 60     public boolean checkForWin() {
 61         boolean result = false;
 62         // Check for win horizontally
 63         for (int row = 0; row < board.length; row++) {
 64             for (int col = 0; col < board[row].length - 3; col++) {
 65                 if (board[row][col] != ' ' && board[row][col] == board[row][col + 1]
 66                         && board[row][col] == board[row][col + 2] && board[row][col] == board[row][col + 3]) {
 67                     return true;
 68                 }
 69             }
 70         }
 71         // Check for win vertically
 72         for (int col = 0; col < board[0].length; col++) {
 73             for (int row = 0; row < board.length - 3; row++) {
 74                 if (board[row][col] != ' ' && board[row][col] == board[row + 1][col]
 75                         && board[row][col] == board[row + 2][col] && board[row][col] == board[row + 3][col]) {
 76                     return true;
 77                 }
 78             }
 79         }
 80 
 81         // Check for win diagonally, from top left
 82         for (int row = 0; row < board.length - 3; row++) {
 83             for (int col = 0; col < board[row].length - 3; col++) {
 84                 if (board[row][col] != ' ' && board[row][col] == board[row + 1][col + 1]
 85                         && board[row][col] == board[row + 2][col + 2] && board[row][col] == board[row + 3][col + 3]) {
 86                     return true;
 87                 }
 88             }
 89         }
 90 
 91         // Check for win diagonally, from top right
 92         for (int row = 0; row < board.length - 3; row++) {
 93             for (int col = 3; col < board[row].length; col++) {
 94                 if (board[row][col] != ' ' && board[row][col] == board[row + 1][col - 1]
 95                         && board[row][col] == board[row + 2][col - 2] && board[row][col] == board[row + 3][col - 3]) {
 96                     return true;
 97                 }
 98             }
 99         }
100         return false;
101 
102     }
103 
104     public char switchPlayer(char currentPlayer) {
105         if (currentPlayer == 'X') {
106             return 'O';
107         } else {
108             return 'X';
109         }
110     }
111 }

 

posted @ 2019-08-16 11:36  北叶青藤  阅读(682)  评论(0)    收藏  举报