gpt4 book ai didi

二维板的 Python 检查列表

转载 作者:行者123 更新时间:2023-11-28 22:58:35 26 4
gpt4 key购买 nike

假设我有一个这样的列表:

board = 
[[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,]

表示二维板上的空间。
如果玩家 1 离开,它将变为 1。
如果玩家二走了,它将变为 2。

获胜条件是:如果一行或一列完全填满,或者对角线填满。

以下是我对水平或垂直获胜者的功能:

def horizontal_winner(board, boxes):
'''
function will find if the horizontal win conditions apply
given 2 inputs. the board, a list and the number of boxes
- board - the 2D board of the game
- boxes - number of boxes per side
'''
for i in range(boxes):
player_1 = 0
player_2 = 0
for j in range(boxes):
if board[i][j] == 1:# first iteration - [1, 0, 0, 0, 0]
player_1 += 1
print("p1: " + str(player_1))
elif board[i][j] == 2:# first iteration - [2, 0, 0, 0, 0]
player_2 += 1
print("p2: " + str(player_2))
if player_1 == boxes:
return True
elif player_2 == boxes:
return False


def vertical_winner(board, boxes):
'''
function will find if the vertical win conditions apply
given 2 inputs. the board, a list and the number of boxes per side
- board - the 2D board of the game
- boxes - number of boxes per side
'''
for i in range(boxes):
player_1 = 0
player_2 = 0
for j in range(boxes):
if board[j][i] == 1:# first iteration - [1, 0, 0, 0, 0]
player_1 += 1
elif board[j][i] == 2:# first iteration - [2, 0, 0, 0, 0]
player_2 += 1
if player_1 == boxes:
return True
elif player_2 == boxes:
return False

如何对角线检查?

最佳答案

首先,要认识到只有 2 条对角线。并且它们上的每个框的坐标是 (i, i) 或 (boxes-i-1, i) 对于 range(boxes) 中的某些 i。这应该可以帮助您弄明白。

关于二维板的 Python 检查列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com