Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - How to Make a Move in Connect Four Game - Please see code below

I'm a pretty new beginner at Python. So far, I've created a Tic Tac Toe game which I used as my foundation for my Connect Four game. However, the mechanics of the game are completely different, because there's no use of rows in Connect Four as the piece drops to the lowest possible place. Below is my what I have so far:

"""
    Author: Victor Xu

    Date: Jan 12, 2021

    Description: An implementation of the game Tic-Tac-Toe in Python,
    using a nested list, and everything else that I've learned so far.
"""

import random


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'."""



    # 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("   0   1   2   3   4   5   6")
    print("   " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][
        4] + " | " + board[0][5] + " | " + board[0][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][
        4] + " | " + board[1][5] + " | " + board[1][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board[2][
        4] + " | " + board[2][5] + " | " + board[2][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board[3][
        4] + " | " + board[3][5] + " | " + board[3][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board[4][
        4] + " | " + board[4][5] + " | " + board[4][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board[5][
        4] + " | " + board[5][5] + " | " + board[5][6])
    print("  ---+---+---+---+---+---+---")
    print("   " + board[6][0] + " | " + board[6][1] + " | " + board[6][2] + " | " + board[6][3] + " | " + board[6][
        4] + " | " + board[6][5] + " | " + board[6][6])
    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 0 and 6, and that square
    is not already occupied, then it will place an 'X' in that square."""

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

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[col][6] == 'O':
            print("Sorry, that column is full. Please try again!
")
        else:
            for row in range(6, 0, -1):
                if board[col][row] == 'O':
                    board[col][row + 1] = 'O'
                    computer_valid_move = True
            if not computer_valid_move:
                board[col][0] = 'O'
                computer_valid_move = True


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

    free_cells = 42
    users_turn = True
    ttt_board = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
                 [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
                 [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
                 [" ", " ", " ", " ", " ", " ", " "]]

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

    display_board(ttt_board)
    if (winner(ttt_board) == 'X'):
        print("Y O U   W O N !")
    elif (winner(ttt_board) == 'O'):
        print("I   W O N !")
    else:
        print("S T A L E M A T E !")
    print("
*** GAME OVER ***
")


# Start the game!
main()

I need help with the make_user_move function. The code under that function is pretty buggy and doesn't do what I want it to do. For one, it only drops pieces in the first column and treats the user's input as a row entry. Second, you can place a piece over another piece, which I don't want. Third, the pieces don't drop to the bottom and stack up. Any help would be greatly appreciated!

question from:https://stackoverflow.com/questions/65851299/how-to-make-a-move-in-connect-four-game-please-see-code-below

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Below are the two functions for the user and computer making their moves, with just a few changes from your original functions.

Firstly, all of the list indices have been swapped in these functions, this solves the problem of the user's input (and computer's move) being treated as a row, not a column.

Next, to solve the problem of moves being placed on top of each other, the following was changed:

  • the first if statement of each function has been changed to check if the cell isn't blank (before, the code only checked if the cell contained a piece of that player, i.e. the computer could place a piece over one of the player's pieces).
  • the for loop has been changed, again checking if the cell is not blank for the same reasons as above.
  • the functions have been changed to return the board, with this value being stored in the main() function's ttt_board list, without this change, the move made by the moving functions would not be stored for subsequent turns, as no value was returned.

These two lines need to be changed in the while loop in main() to take the returned value from the moving functions and update the main ttt_board:

make_user_move(ttt_board)

becomes

ttt_board = make_user_move(ttt_board)

and

make_computer_move(ttt_board)

becomes

ttt_board = make_computer_move(ttt_board)

The updated moving functions:

def make_user_move(board):
    valid_move = False
    while not valid_move:
        col = int(input("What col would you like to move to (0-6):"))
        if board[0][col] != ' ':
            print("Sorry, that column is full. Please try again!
")
        else:
            for row in range(6, -1, -1):
                if board[row][col] == ' ' and not valid_move:
                    board[row][col] = 'X'
                    valid_move = True
    return board

def make_computer_move(board):
    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!
")
        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

See full version of the code here:

https://pastebin.com/NYe8QRgT


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...