简体   繁体   English

如何使用预设列表在python中编写井字游戏/连接四的检查功能,如下面的代码所示?

[英]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.所以我有一个任务,我们有一个已经给定的列表或一组列表,board1、board2 和 board3,对于这些列表,我们必须根据检查功能对它们是否获胜进行编码。 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.对于主检查功能,我指的是没有行或列等要检查的功能,我指的是代码中名为 check(list) 的功能。 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.除了 check(list) 下的代码外,所有东西都是他给的,所以 def check(list) 本身是给的,但它下的代码我自己试过了。 And the code under check_column.以及 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.其余的都是教授给的,要么自己编写一部分代码(例如:check_diagonal 函数,该函数已提供,但您需要自己编写代码),或者已经有一些东西可以帮助您完成练习。 The task isn't that hard but I am a beginner in python and just can't seem to find the right thing.任务并不难,但我是 python 的初学者,似乎找不到合适的东西。 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.我需要尽快知道这一点,因为我们必须在 2021 年 10 月 25 日星期一晚上 11:30(中欧时间)晚上提交任务。

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!就像连接4! For example length 3 if gameboard is 3x3.例如,如果游戏板是 3x3,则长度为 3。 How do I change the check(list) function so that it provides the desired output?如何更改check(list)函数以提供所需的输出? 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.我什至无法尝试编写 check_diagonal 函数,因为我还没有通过 check(list) 函数。 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.我用 check(list) 函数得到的最好的结果是有必要的输出,但没有实际检查是否有赢家。 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?如何更改check(list)函数以提供所需的输出?

Here is how you would fix the output continuously returning 'no profit' for the rows and columns:以下是如何修复输出连续为行和列返回'no profit'的方法:

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?编辑:或者,在这种情况下,您可能正在寻找all而不是any 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.注意:我在这里更改了名为list的变量,因为覆盖名为 list 的内置类型通常不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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