简体   繁体   中英

How do I code the check function for tic-tac-toe/connect four in python with a preset list as shown in code below?

Additional Info:

So I have a task where we have an already given list or a set of lists, board1, board2 and board3, and with those lists we have to code wheter or not they won according to the check function. We have to check this for the row, column and diagonals. Now I am really struggling with the main check function. I have searched online and there are a lot of forums and videos about tic tac toe and/or connect four but almost all of them include inputs. Since I already have preset answers, meaning I do not have to input anything, I don't really know how to handle this main check function. With main check function I mean the one where you don't have row or column and so on next to check, I mean the one named check(list) in the code. Most of the code was given by the professor himself already. Everything was given by him except for the code under check(list), so def check(list) itself was given but the code under it I tried myself. And the code under check_column. All the rest was given by the professor, either to code a part of it yourself (for example: the check_diagonal function, that one was given but you need to code what it has to do yourself) or to already have something to help you finish the excercice. The task isn't that hard but I am a beginner in python and just can't seem to find the right thing. A sample output was also given at the bottom of the whole code. I need to know this ASAP because we have to hand in the task tonight monday 10/25/2021 at 11:30 pm Central European Time.

The intent of the exercise is to check if you have the number of symbols next to each other equal to the length or width of the matrix. Just like connect 4! For example length 3 if gameboard is 3x3. How do I change the check(list) function so that it provides the desired output? Thank you to everyone helping!

# Task 4: X-in-a-row


# this function allows to print the game board
# it can serve as inspiration for the solution
def print_board(board):
    for i in range(0, len(board)):
        row_string = ''
        for j in range(0, len(board)):
            # here we use %2s to align the elements nicely
            row_string += '%2s' % board[i][j]
        print(row_string)


#
# this feature checks if a list consists of a winning combination
# this function is called to either a row, column, or diagonal
# the entered list must therefore be as long/wide as the game board
# (e.g. length 3 if the game board is 3x3)
# and returns True/False
# for information, the winning game can be printed (but must not be returned)
def check(list):
    list = []
    for y in range(0, len(list)):
        list_string = ''
        for x in range(0, len(list)):
            if list[x][y] == 'X':
                return True
    return False




    # REPLACE THIS WITH YOUR CODE
    # ...
    # REPLACE THIS WITH YOUR CODE


# this function serves as an example for the other functions you need to complete
# the output is either the row number (counting from 0) or 'no profit'
def check_rows(board):
    for row in range(0, len(board)):
        if check(board[row]):
            return row
    return 'no profit'


# this function checks the columns 1-by-1
# the output is either the column number (counting from 0) or 'no profit'
def check_columns(board):
    for column in range(0, len(board)):
        if check(board[column]):
            return column
    return 'no profit'

    # REPLACE THIS WITH YOUR CODE
    # ...
    # REPLACE THIS WITH YOUR CODE


# this function is obviously the most difficult and checks the 2 diagonals
# you may first check the diagonal from top left to bottom right (diagonal 1)
# then bottom left to top right (diagonal 2)
# the function returns either 'diagonal 1', 'diagonal 2', or 'no profit'
def check_diagonal(board):
    # here is an example of how to check the elements
    # save them in this list
    elements = []

    # REPLACE THIS WITH YOUR CODE
    # ...
    # REPLACE THIS WITH YOUR CODE

    # and then check them here
    if check(elements):
        return 'diagonal 1'

    elements = []

    # REPLACE THIS WITH YOUR CODE
    # ...
    # REPLACE THIS WITH YOUR CODE

    if check(elements):
        return 'diagonal 2'
    return 'no profit'


# you can assume that only O/X is used and that the board is always square
# note: these are capital o's and not 0
board_1 = [
    ['X','X','X','X'],
    ['','','O','O'],
    ['X','O','X','X'],
    ['O','X','O','X']]

print('\nboard 1:')
print_board(board_1)

print('Row:', check_rows(board_1))
print('Column:', check_columns(board_1))
print('Diagonal:', check_diagonal(board_1))

board_2 = [
    ['X','X',''],
    ['X','O','X'],
    ['X','X','O']]

print('\nboard 2:')
print_board(board_2)

print('Row:', check_rows(board_2))
print('Column:', check_columns(board_2))
print('Diagonal:', check_diagonal(board_2))

board_3 = [
    ['O','X','X','X'],
    ['','O','O','O'],
    ['X','O','O','X'],
    ['O','X','O','O']]

print('\nboard 3:')
print_board(board_3)

print('Row:', check_rows(board_3))
print('Column:', check_columns(board_3))
print('Diagonal:', check_diagonal(board_3))


# Sample output:
# Board 1:
#  X X X X
#      O O
#  X O X X
#  O X O X
# X won (this is printed by the check() function and is optional)
# Row: 0
# Column: no profit
# Diagonal: no profit
#
# Board 2:
#  X X
#  X O X
#  X X O
# Row: no profit
# X won
# Column: 0
# Diagonal: no profit
#
# Board 3:
#  O X X X
#    O O O
#  X O O X
#  O X O O
# Row: no profit
# Column: no profit
# O won
# Diagonal: diagonal 1

Please edit the question to remove any unnecessary info that is not needed. It will be easier for others to help if they can more easily understand what the problem is.

In this case, the following lines in the question seems to identify the problem:

I have tried so much the last couple of days but can't find anything. I haven't even been able to try to code the check_diagonal function because I haven't got past the check(list) one. The best I have gotten with the check(list) function is to have the necessary output but without it actually checking if there is a winner. So every answer would be 'no profit'. I hope someone can help me thank you so much in advance for doing so.

Which can be stated more clearly as:

How do I change the check(list) function so that it provides the desired output?

Here is how you would fix the output continuously returning 'no profit' for the rows and columns:

def check(L: list) -> bool:
    for y in range(0, len(list)):
        if L[y] == 'X':
            return True
    return False

Which can be reworded more concisely as follows:

def check(L: list) -> bool:
    return any(elem == 'X' for elem in L)

Edit : Or maybe you're looking for all instead of any in this case? The difference is that the latter check is any condition is true, but the first uses an and condition to evaluate the expression.

def check(L: list) -> bool:
    return all(elem == 'X' for elem in L)

NB: I've changed the variable named list here, because it's generally not a good idea to override a builtin type named list.

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