Python连接四。使计算机m

2024-10-01 17:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来完成我的连接四任务。我的电脑移动功能有问题。在我的作业中,我想用一张单子当黑板。列表中的列表数是行。列表中的项是cols。在

board=[[" "," "," "," "," "],
       [" "," "," "," "," "],
       [" "," "," "," "," "],
       [" "," "," "," "," "],
       [" "," "," "," "," "]]

有5行5列。因此有25个游离细胞。main函数循环25次并调用make_computer_move功能。Thedisplay_board函数不重要。问题出在make_computer_move。它应该充满整个电路板,因为有25个自由单元和主回路25次。但没有。还有空白。 它也不会打印出移动的坐标。我放置了一个print语句,以便每当发生有效的移动时,都会打印坐标。我注意到,有时在循环中,董事会保持不变,什么也没发生。 我被难住了:/

^{pr2}$

Tags: 函数功能board列表movemakemain作业
3条回答

上面的代码工作得很好。它使make_computer_move(board, avail_col)在填充给定列时将列号返回给main。在主菜单中,此栏在再次调用make_computer_board之前取出:

import random

def display_board(board):
    col = "   "
    cols = len(board[0])
    for index1 in range(cols):
        col += "%i   " % index1
    print col
    for index2 in range(len(board)):
        print str(index2) + ": " + " | ".join(board[index2]) + " |"
        print "  " + "---+" * cols


def make_computer_move(board, avail_cols):
    col = random.choice(avail_cols) 
    for row in range(len(board)-1, -1, -1):            # counts from bottom of board and up
        if board[row][col] == " ":                      # if there is a blank space, put a "O" and break
            print "The pairing is (%i,%i)" % (row,col)  #Print the coordinates
            board[row][col] = 'O'
            break

    if row == 0:      #arrives to the last row
        return col


def main():
    board = [[" ", " ", " ", " ", " "] for i in range(5)]
    avail_cols = range(len(board[0]))
    display_board(board)
    for counter in range(25):
        filled = make_computer_move(board, avail_cols)
        display_board(board)
        if filled is not None: avail_cols.remove(filled)


main()

注:

  1. 随机导入现在位于顶部。在
  2. 代码在PEP-8之后得到了一些美化。在
  3. 我准备了一份清单
  4. display_board(board)的两个调用。第一个平局开始 步骤,secon one已在make_computer_move之后移动到 程序完成后画最后一个图形
  5. 用%插值法简化某些直线

还有一些效率低下的地方。例如,每次调用函数时都要计算len(board[0]),因为板始终保持相同的大小。在

最简单的是,如果make_computer_move()在该列中找不到空闲槽,则需要再次调用它自己,就像现在,您设置了一个新列,然后对它不做任何操作。在

def make_computer_move(board):
    import random
    col=random.randint(0,(len(board[0])-1)) 
    for row in range(len(board)-1,-1,-1): # counts from the bottom of the board and up
        if board[row][col]==" ": #if there is a blank space it will put a "O" and break
            print "The pairing is("+str(row),str(col)+")" #Print the coordinates
            board[row][col] = 'O'
            break
    else: #if the break does not occur this else statement executes
       make_computer_move(board)

请注意,你所采用的方法并不是特别有效,因为没有保证它会找到一个空闲的时段。您至少应该做一些事情,比如让列\u not_full=[0,1,2。。。n] 然后在最后一个插槽填满时删除列,然后使用随机选择(columns\u not_full)获取要在其中播放的列。在

这将为您提供一个随机打开的列(或行,取决于您如何看待它)的索引。在

openColumns = [i for i in range(len(board)) if board[i].count(' ') > 0]
if openColumns: ComputerChoice = openColumns[random.randint(0, len(openColumns)]
else: #do something if there are no open columns (i.e. the board is full)

相关问题 更多 >

    热门问题