【发布时间】:2020-06-27 00:59:53
【问题描述】:
我在下面有此代码作为 python 棋盘游戏的一部分 - 为什么即使棋盘未满,代码也会结束?
drop_piece 函数代码应该一直运行到板子已满,但最后的板子未满。
import random
ROWS = 6
COLUMNS = 7
PIECE_NONE = ' '
PIECE_ONE = 'x'
PIECE_TWO = 'o'
# Board Functions
def create_board(rows=ROWS, columns=COLUMNS):
''' Creates empty Connect 4 board '''
board = []
for row in range(rows):
board_row = []
for column in range(columns):
board_row.append(PIECE_NONE)
board.append(board_row)
return board
def print_board( board ):
''' Prints Connect 4 board '''
for row in board: # like for i in list, the board has 6 items or rows,
print ('| ' + ' | '.join(row) + ' |') # front and end has a '|', in the middle, for each row which has 7 items, join the 7 items by each '|', now it prints 7 slots.
print("\n---------print: 7 items, join the 7 items by each '|', now it prints 7 slots--------------\n" )
#print_board( create_board( ) )
def drop_piece(board, column, piece):
''' Attempts to drop specified piece into the board at the
specified column
If this succeeds, return True, otherwise return False.
'''
for row in reversed(board): # reverse the board
if row[column] == PIECE_NONE: # if each row from bottom to top, row[column] blank, drop ball, if not, what about the next one, i.e. second last row,
row[column] = piece
return True # this code should run until the board is FULL, but the board at last is NOT FULL.
return False
print("\n---------print while drop_piece( )------------\n" )
import random
Board = create_board()
Turn=0
Players=(PIECE_ONE, PIECE_TWO)
while drop_piece(Board, random.randint(0, COLUMNS - 1), Players[Turn % 2]):
# while drop_piece( ) is True:
print_board(Board)
print()
Turn += 1
print ('Board FULL!')
下面是输出的最后一部分。董事会未满。 drop_piece 代码应该一直运行到板子满为止,对吧?但它没有。
| | | | | | o | |
| | | x | x | | o | |
| | | x | x | | o | |
| | | o | o | x | o | x |
| | | o | x | x | x | o |
| o | | x | o | o | x | x |
Board FULL!
【问题讨论】: