繁体   English   中英

Python Connect四。 使计算机移动

[英]Python Connect Four. Making the computer move

我的四连环作业需要一些帮助。 我的计算机移动功能有问题。 在我的作业中,我想使用一个清单作为董事会。 列表中的列表数是该行。 列表中列表中的项目是列。

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

有5行和5个列。 因此有25个自由细胞。 main函数循环25次,并调用make_computer_move function.The display_board功能并不重要。 问题出在make_computer_move 它应该充满整个电路板,因为有25个空闲单元,并且主循环有25次。 但事实并非如此。 剩余空格。 此外,它不会打印其移动的坐标。 我放置了一条打印语句,以便每当发生有效移动时,都将打印坐标。 我注意到有时板在循环中保持不变,什么也没发生。 我很沮丧:/

def display_board(board):
    col="   "
    for index1 in range(len(board[0])):
        col+=str(index1)+"   "
    print col
    for index2 in range(len(board)):
        print str(index2)+": "+" | ".join(board[index2])+" |"
        print "  "+"---+"*(len(board[0]))
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
        col=random.randint(0,(len(board[0])-1)) 
def main():
    board=[[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "]]
    for counter in range(25):
        display_board(board)
        make_computer_move(board)
main()

最简单的是,如果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)

请注意,您使用的方法并不是特别有效,因为没有保证人会找到可用的插槽。 您可能想要至少做一些事情,例如,使columns_not_full = [0、1、2,... n],然后在填充最后一个插槽时删除列,并使用random.choice(columns_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)

首先,您应该测试至少一个空白空间,并且通常导入是程序的顶部。

import random

def make_computer_move(board): for row in board: ## look for first empty space if " " in row: while True: ## infinite loop col=random.randint(0,(len(board[0])-1)) for row in range(len(board)-1,-1,-1): if board[row][col]==" ": print "The pairing is("+str(row),str(col)+")" #Print the coordinates board[row][col] = 'O' return board print "All squares filled -- Game Over"

Another alternative is to create a list of available spaces and choose

available = [] for row in range(5): for col in range(5): if board[row][col] == " ": available.append([row, col]) move = random.choice(available)

上面的代码运行完美。 它使make_computer_move(board, avail_col)将给定列填充后的列号返回给main。 在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一个移至make_computer_move之后绘制最后一个图形
  5. 使用%插值来简化某些行

仍然存在一些效率低下的问题。 例如,在不需要此函数时每次调用len(board[0])都需要计算len(board[0])因为该板始终保持相同的大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM