为connect4创建一个(非常简单的)计算机对手

时间:2017-04-17 10:54:11

标签: python-3.x

我目前在编写应该返回建议移动的函数时遇到问题,即连接游戏4的简单计算机对手。 以下是我编写的一些函数(并且对于我测试的情况正常工作)但是在计算机多功能函数中使用。

import random
#board: a list containing 6 lists with 7 elements each (a connect4 board)
#0 represents an empty space, and 1,2 represent player1 and player2
#turn: whose turn it is (i.e. player1 or player2)
#move: column they want to make a move in (i.e 0-6, but will be 1-7 to the            player)

def validmoves(board):
    """This function iterates through the board to find all the valid moves 
(i.e. it excludes the columns that are filled) and returns the list of
columns with valid moves"""
vm = []
for j in range(7):
    i = 5
    while vm.count(j) == 0 and i>=0:
        if board[i][j] == 0:
            vm.append(j)
        i -= 1    
return vm

def makemove(board,move,turn):
"""This function places turn's player piece in the move'th column and 
returns the board"""
for i in reversed(board):
    if i[move] == 0:
        i[move] = turn
        return board

def winner(board,turn):
"""This function checks if the player who just played a turn has won"""
#horizontals
for i in board:
    for j in range(4):
        if i[j]==turn and i[j+1]==turn and i[j+2]==turn and i[j+3]==turn:
            return True
#verticals
for j in range(7):
    for i in range(3):
        if board[i][j]==turn and board[i+1][j]==turn and board[i+2][j]==turn and board[i+3][j]==turn:
            return True
#positive diagonals
for j in range(4):
    for i in range(3):
        if board[i][j]==turn and board[i+1][j+1]==turn and board[i+2][j+2]==turn and board[i+3][j+3]==turn:
            return True
#negative diagonals
for j in range(4):
    for i in range(5,2,-1):
        if board[i][j]==turn and board[i-1][j+1]==turn and board[i-2][j+2]==turn and board[i-3][j+3]==turn:
            return True
return False

以下是我遇到问题的代码

def computeropponent(board,turn):
#the following defines the other player in the context of this function
if turn == 1:
    notturn = 2
elif turn == 2:
    notturn = 1
"""for the following loops, it only computes the first loop and then skips straight to
the last line."""
for move in validmoves(board):
    if winner(makemove(board,move,turn),turn)==True:
        return move
for move in validmoves(board):
    if winner(makemove(board,move,notturn),turn)==True:
        return move
return random.choice(validmoves(board))

即。如果我要交换for循环的顺序(或设置转为1)     计算机对手),它将返回正确答案(在下面的测试中应为0),但在这种情况下,它只返回有效移动列表中的随机元素。

board = [[0,0,0,0,0,0,0],
     [0,0,0,0,0,0,0],
     [0,0,0,0,0,0,0],
     [0,0,0,0,1,2,0],
     [0,0,0,1,2,2,0],
     [0,1,1,1,2,1,0]] 
print(validmoves(board))
print(computeropponent(board,2))

我提前为我的帖子的杂乱代码和长度道歉。我没有编程很长时间,这是我第一次在stackexchange上发帖,并提前感谢您的帮助。

0 个答案:

没有答案