简体   繁体   中英

Issue with Connect Four Board

I'm trying to allow the user to input the # of rows and columns that they'd like in their connect 4 game, so I'm trying to use their input to create the board. I'm trying to create a nested list so that my other code works. I've been trying for the past 2 hours, by searching the web and racking my brains for an answer. Here is the code:

import random
import ast


def winner(board):
    """This function accepts the Connect Four board as a parameter.
    If there is no winner, the function will return the empty string "".
    If the user has won, it will return 'X', and if the computer has
    won it will return 'O'."""
    for row in range(7):
        count = 0
        last = ''
        for col in range(7):
            row_win = board[row][col]
            if row_win == " ":
                count = 0
                continue
            if row_win == last:
                count += 1
            else:
                count = 1
            if count >= 4:
                return row_win
            last = row_win

    for col in range(7):
        count = 0
        last = ''
        for row in range(7):
            col_win = board[row][col]
            if col_win == " ":
                count = 0
                continue
            if col_win == last:
                count += 1
            else:
                count = 1
            if count >= 4:
                return col_win
            last = col_win

    for row in range(7):
        for col in range(7):
            try:
                if (board[row][col] == board[row + 1][col + 1] and board[row + 1][col + 1] == board[row + 2][
                    col + 2] and
                    board[row + 2][col + 2] == board[row + 3][col + 3]) and (
                        board[row][col] != " " or board[row + 1][col + 1] != " " or board[row + 2][col + 2] != " " or
                        board[row + 3][col + 3] != " "):
                    return board[row][col]
            except:
                IndexError

    for row in range(7):
        for col in range(7):
            try:
                if (board[row][col] == board[row + 1][col - 1] and board[row + 1][col - 1] == board[row + 2][
                    col - 2] and
                    board[row + 2][col - 2] == board[row + 3][col - 3]) and (
                        board[row][col] != " " or board[row + 1][col - 1] != " " or board[row + 2][col - 2] != " " or
                        board[row + 3][col - 3] != " "):
                    return board[row][col]
            except:
                IndexError

    # No winner: return the empty string
    return ""


def display_board(board):
    """This function accepts the Connect Four board as a parameter.
    It will print the Connect Four board grid (using ASCII characters)
    and show the positions of any X's and O's.  It also displays
    the column numbers on top of the board to help
    the user figure out the coordinates of their next move.
    This function does not return anything."""

    # print(" 1   2   3   4   5   6   7")
    header = "  "
    i = 1
    while i < len(board) + 1:
        header = header + str(i) + "   "
        i += 1
    header = header + str(i)

    print(header)

    for row in board:
        print(" ", " | ".join(row))
        print(" ---+---+---+---+---+---+---")
    print()

    #
    # header = "  "
    # pipe_line = "  |"
    # separator = "---+"
    #
    # for row_num in range():
    #     header = header + str(row_num)
    #     pipe_line = pipe_line + " " + " | ".join(row))
    #     separator = separator + "---+"
    # print()


def make_user_move(board):
    """This function accepts the Connect Four board as a parameter.
    It will ask the user for a row and column.  If the row and
    column are each within the range of 1 and 7, and that square
    is not already occupied, then it will place an 'X' in that square."""

    valid_move = False
    while not valid_move:
        try:
            col = int(input("What col would you like to move to (1-7): "))
            if board[0][col - 1] != ' ':
                print("Sorry, that column is full. Please try again!\n")
            else:
                col = col - 1
                for row in range(6, -1, -1):
                    if board[row][col] == ' ' and not valid_move:
                        board[row][col] = 'X'
                        valid_move = True
        except:
            ValueError
            print("Please enter a valid option! ")

    return board


def make_computer_move(board):
    """This function accepts the Connect Four board as a parameter.
    It will randomly pick row and column values between 0 and 6.
    If that square is not already occupied it will place an 'O'
    in that square.  Otherwise, another random row and column
    will be generated."""
    computer_valid_move = False
    while not computer_valid_move:
        col = random.randint(0, 6)
        if board[0][col] != ' ':
            print("Sorry, that column is full. Please try again!\n")
        else:
            for row in range(6, -1, -1):
                if board[row][col] == ' ' and not computer_valid_move:
                    board[row][col] = 'O'
                    computer_valid_move = True
    return board


def main():
    """The Main Game Loop:"""

    # free_cells = 42
    # users_turn = True
    # cf_board = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "]]

    cf_board = []
    row = int(input("How many rows do you want your game to have? "))
    col = int(input("How many columns do you want your game to have? "))
    free_cells = col * row
    row_str = "\" \""
    board_str = "\" \""
    i = 0
    j = 0

    while i < col-1:
        row_str = row_str + "," + "\" \""
        i += 1
    row_str = "'" + row_str + "'"
    board_str = row_str + ","
    while j < row-1:
        board_str = board_str + row_str + ","
        j += 1
    Input = [board_str]
    cf_board = [list(ast.literal_eval(x)) for x in Input]
    # for i in range(row-1):
    #     cf_board.append(row_str)

    while not winner(cf_board) and (free_cells > 0):
        display_board(cf_board)
        if users_turn:
            cf_board = make_user_move(cf_board)
            users_turn = not users_turn
        else:
            cf_board = make_computer_move(cf_board)
            users_turn = not users_turn
        free_cells -= 1

    display_board(cf_board)
    if (winner(cf_board) == 'X'):
        print("Y O U   W O N !")
    elif (winner(cf_board) == 'O'):
        print("T H E   C O M P U T E R   W O N !")
    elif free_cells == 0:
        print("S T A L E M A T E !")
    print("\n*** GAME OVER ***\n")


# Start the game!
main()

I'd like it to become something formatted like this;

    # cf_board = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
    #             [" ", " ", " ", " ", " ", " ", " "]]

Where the row and col depends on the user. I've tried achieving that, but I only get this huge list that's not separated by the # of rows and columns.

TL;DR

Please help me fix my code at main(), where I'm trying to construct a board with the user's inputs

Please try to ask questions only using a minimal reproducible example. If you are only trying to solve the problem of constructing a board from user input then only post the necessary code relating to that. To generate a list of lists of open spaces you could do something like this.

row = int(input("How many rows do you want your game to have? "))
col = int(input("How many columns do you want your game to have? "))
cf_board = []
rowLst = []

for i in range(row):
    for j in range(col):
        rowLst.append(" ")
    cf_board.append(rowLst.copy())
    rowLst.clear()

print(board)

for j in range(col) appends an open space to a new list. After that finishes that list is appended to the main board list and then cleared to go onto the next row.

getting that board is pretty simple. Don't need eval or anything like that.

Just do cf_board = [[" "]*col]*row to put as many space entries and lists inside as you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM