【问题标题】:python print board game - Why does the code end even if the board is NOT FULL?python print board game - 为什么即使板子没有满,代码也会结束?
【发布时间】: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!

【问题讨论】:

    标签: python printing


    【解决方案1】:

    当一列填满时,您的代码会返回“无”,这相当于 python 中的 False。我已修改您的代码以跟踪该列,并且仅在所有列已满时才返回 false。

    import random
    
    
    ROWS       = 6
    COLUMNS    = 7
    
    PIECE_NONE = ' '
    PIECE_ONE  = 'x'
    PIECE_TWO  = 'o'
    FULL_COLUMS = ["has_space"] * COLUMNS # List to keep track of full colums
    
    
    # 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.
        '''
    
        ''' ************** Debug Notes  ************************
            Your code in this loop will and return None once the given 'column' is full. This is your bug :)
            To correct it, you would need to check if all columns are full, and only then do you return full.
            
            ***There are several ways of doing this. I will use the simplest one. So, I will keep track of every full colums.
            Therefore, every time the for loop is exectuted to completion, I will take the value of 'column' and mark that 
            the column corespoding to that number is full. I will keep doing this until all colums are full.
            To return false, all columns will need to be full. 
        '''
        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.
        #if we get here, one of the colums if full, so lets mark that
        FULL_COLUMS[column] = "Full"
        return "has_space" in FULL_COLUMS # this will return false only if all colums are full
    
    
    
    
    
    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!')
    

    这是我修改后得到的输出

    | o | o | o | x | x | x | o |
    | x | o | o | o | o | x | x |
    | x | o | x | o | x | o | o |
    | o | x | o | o | o | x | x |
    | x | o | o | x | x | x | o |
    | o | x | o | o | x | x | x |
    
    Board FULL!
    

    【讨论】:

      【解决方案2】:

      drop piece 函数只测试使用该函数输入的列的所有行,而不是所有列的所有行。因此,当指定列已满时,droppiece 函数将返回 False。为了测试整个板子何时已满,您必须使用另一个函数来测试它,如下所示:

      def board_is_not_full():
          for row in board:
              for column in row:
                  if row[column] == PIECE_NONE:
                      return True
          return False
      

      【讨论】:

      • 我在 while 循环的顶部添加了 board_is_not_full(Board) 条件,但是下面出现了这个错误。 while board_is_not_full(Board): while drop_piece(Board, random.randint(0, COLUMNS - 1), Players[Turn % 2]): Traceback (最近一次通话最后一次): File "e14_7_10_(a)_Connect4_game_drop_piece3.py", line 117, 在 while board_is_not_full(Board): File "e14_7_10_(a)_Connect4_game_drop_piece3.py", line 55, in board_is_not_full if row[column] == PIECE_NONE: TypeError: list indices must be integers or slices, not str
      • 从 row[column] == PIECE_NON 更改为 column == PIECE_NON,现在可以使用了。伟大的。 def board_is_not_full(): for row in board: for column in row: if column == PIECE_NONE: return True return False
      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多