簡體   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