我想要做的是循環板中的元素,尋找「P」,然後檢查是否有5「 P「連續(向下,可以這麼說)。請參閱代碼中的註釋以獲得進一步解釋仍然,inRow給我輸出15.循環列表(嵌套for循環)不工作,因爲我想它
提示:五個「P」不應該是固定的,而是由玩家放置,但對於這個例子,我只是放置了固定的。
board = [['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']]
# has 10 rows, with 10 elements in each
inRow=0
for y in range(10): # Loops over each row (y-index)
x=0 # x-index resets each new y-index loop (start on the first element (0) of each row)
for pos in board[y]: # pos loops over all elements in current row
if pos is "P": # checks if pos is "P"
for i in range(5): # loops over 0, 1, 2, 3, 4
if board[y+i][x] is "P": # when i=0, board[y+i][x] is ought to be where we find the first "P", then check if the following rows (we add +1 to y for each loop) is also "P"
inRow += 1 # Counter to see if we got 5 in a row
break
x+=1
print(inRow)
作者希望'inRow'是'5'而不是'15'。 – huu
不要在字符串中使用'is'。 '是'測試相同的對象,而不是相等的字符串。 – Daniel
你是否需要將它製作成嵌套循環?如果是這樣,一個建議是首先在列上循環,然後在行上循環。 – pekapa