Python:AI并不总是把他的动作放在b船上



在b-ship的这个代码中:

import random
import time
def drawboard(aiboard,playerboard):
    print(' Opponent's          Your')
    print('    Ships            Ships')
    print('|   |   |   |    |   |   |   |')
    print('| ' + aiboard[7] + ' | ' + aiboard[8] + ' | ' + aiboard[9] + ' |    | ' + playerboard[7] + ' | ' + playerboard[8] + ' | ' + playerboard[9] + ' |')
    print('|   |   |   |    |   |   |   |')
    print('-------------    -------------')
    print('|   |   |   |    |   |   |   |')
    print('| ' + aiboard[4] + ' | ' + aiboard[5] + ' | ' + aiboard[6] + ' |    | ' + playerboard[4] + ' | ' + playerboard[5] + ' | ' + playerboard[6] + ' |')
    print('|   |   |   |    |   |   |   |')
    print('-------------    -------------')
    print('|   |   |   |    |   |   |   |')
    print('| ' + aiboard[1] + ' | ' + aiboard[2] + ' | ' + aiboard[3] + ' |    | ' + playerboard[1] + ' | ' + playerboard[2] + ' | ' + playerboard[3] + ' |')
    print('|   |   |   |    |   |   |   |')
def playerhitai(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots):
    if players_chosen_hit in aishipplaces[0] or players_chosen_hit in aishipplaces[1]:
        aiboard[players_chosen_hit] = 'x'
        drawboard(aiboard,playerboard)
    else:
        aiboard[players_chosen_hit] = 'o'
        drawboard(aiboard,playerboard)
def hitaroundhit(aiboard, playerboard,aishipplaces,players_chosen_hit,usershipspots):
    spots = {1:[2,4],2:[1,3,5],3:[2,6],4:[1,5,7],5:[2,4,6,8],6:[3,5,9],7:[4,8],8:[5,7,9],9:[8,6]}
    spot_dict = random.choice(spots[players_chosen_hit])
    if playerboard[spot_dict] == 's':
        pickX(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots)
        playerhitai(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots)
    else:
        playerboard[spot_dict] = 'o'
        playerhitai(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots)
def pickX(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots,aitakenmoves):
    x = [1,2,3,4,5,6,7,8,9]
    firsthitattempt = random.choice(x)
    while x in aitakenmoves:
        firsthitattempt = random.choice(x)
    return firsthitattempt,aitakenmoves
def aihitplayer(aiboard,playerboard, usershipspots,players_chosen_hit,aishipplaces,aitakenmoves):
    x,z = pickX(aiboard,players_chosen_hit,aishipplaces,playerboard,usershipspots,aitakenmoves)
    if (aiboard[aishipplaces[0][0]] == 'x') and (aiboard[aishipplaces[0][1]] == 'x') and (aiboard[aishipplaces[1][0]] == 'x') and (aiboard[aishipplaces[1][1]] == 'x') and (aiboard[aishipplaces[1][2]] == 'x'):
        return z
    else:
        time.sleep(1)
        print("nComputer's turn.n")
        time.sleep(1)
        if x in usershipspots:
            playerboard[x] = 'x'
            drawboard(aiboard,playerboard)
        else:
            playerboard[x] = 'o'
            drawboard(aiboard,playerboard)
    return z
def getShipInfo(ship,possibleusershipplaces,usershipspots,playerboard):
    while True:
        try:
            ship = int(input('Enter the 5 locations of your ship. Start with ship one (2 spaces) then do ship two (3 spaces).'))
            if ship in possibleusershipplaces:
                break
        except ValueError:
            time.sleep(0.5)
            print("nInvalid entryn")
            time.sleep(0.5)
    while ship in usershipspots:
        try:
            ship = int(input('Spot already taken.'))
            if ship not in possibleusershipplaces:
                while True:
                    try:
                        ship = int(input('1-9 only!'))
                    except (ValueError, IndexError):
                        print('invalid input')
        except (ValueError, IndexError):
            time.sleep(0.5)
            print("nInvalid entryn")
            time.sleep(0.5)    
    playerboard[ship] = 's'
    usershipspots.append(ship)
    return playerboard,usershipspots
def ascii():
    print('''    dMMMMb  .aMMMb dMMMMMMP dMMMMMMP dMP     dMMMMMP .dMMMb  dMP dMP dMP dMMMMb''')
    time.sleep(0.02)
    print('''   dMP"dMP dMP"dMP   dMP      dMP   dMP     dMP     dMP" VP dMP dMP amr dMP.dMP''')
    time.sleep(0.02)
    print('''  dMMMMK" dMMMMMP   dMP      dMP   dMP     dMMMP    VMMMb  dMMMMMP dMP dMMMMP" ''')
    time.sleep(0.02)
    print(''' dMP.aMF dMP dMP   dMP      dMP   dMP     dMP     dP .dMP dMP dMP dMP dMP''')
    time.sleep(0.02)
    print('''dMMMMP" dMP dMP   dMP      dMP   dMMMMMP dMMMMMP  VMMMP" dMP dMP dMP dMP''')                             
    time.sleep(1)
def playagain():
    x = input("Play again? y/n")
    if x == 'yes' or x == 'y' or x == 'Yes' or x == 'Y':
        main()
    else:
        pass
def main():
    print()
    ascii()
    print()
    time.sleep(1)
    print('''
############################################################################
# Instructions:                                                            #
# You have a 3x3 board. So does the AI.                                    #
# Each person has 2 ships. One has a length of 2, other has a length of 3. #
# You can place the ships horizantally or vertically, not diagonally.      #
# You must try to hit the AI ships. Each move you get one shot.            #
# The player and AI alternates back and forth.                             #
# A hit is X and a miss is O. Your ships are designated with an S.         #
# Whoever hits all of the other's ships first, wins the game.              #
############################################################################
''')
    time.sleep(5)
    print()
    aitakenmoves = []
    twoships = [[1,2], [2,1], [1,4], [4,1], [2,3], [3,2], [2,5], [5,2], [3,6], [6,3], [4,5], [5,4], [4,7], [7,4], [5,6], [6,5], [5,8], [8,5], [6,9], [9,6], [7,8], [8,7], [8,9], [9,8]]
    threeships = [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,2,1], [3,1,2], [1,4,7], [1,7,4], [4,1,7], [4,7,1], [7,4,1], [7,1,4], [2,5,8], [2,8,5], [5,8,2], [5,2,8], [8,5,2], [8,2,5], [3,6,9], [3,9,6], [6,9,3], [6,3,9], [9,6,3], [9,3,6], [4,5,6], [4,6,5], [5,6,4], [5,4,6], [6,5,4], [6,4,5], [7,8,9], [7,9,8], [9,8,7], [9,7,8], [8,7,9], [8,9,7]]
    shipspots1 = random.choice(twoships)
    shipspots2 = random.choice(threeships)
    while (shipspots1[0] in shipspots2) or (shipspots1[1] in shipspots2):
        shipspots1 = random.choice(twoships)
        shipspots2 = random.choice(threeships)
    aishipplaces = [shipspots1,shipspots2]
    aiboard = [' ' for i in range(10)]
    playerboard = [' ' for i in range(10)]
    sh1sp1,sh1sp2,sh2sp1,sh2sp2,sh2sp3 = '','','','',''
    possibleusershipplaces = [1,2,3,4,5,6,7,8,9]
    players_inputted_hits = []
    usershipspots = []
    playerboard,usershipspots = getShipInfo(sh1sp1,possibleusershipplaces,usershipspots,playerboard)
    playerboard,usershipspots = getShipInfo(sh1sp2,possibleusershipplaces,usershipspots,playerboard)
    playerboard,usershipspots = getShipInfo(sh2sp1,possibleusershipplaces,usershipspots,playerboard)
    playerboard,usershipspots = getShipInfo(sh2sp2,possibleusershipplaces,usershipspots,playerboard)
    playerboard,usershipspots = getShipInfo(sh2sp3,possibleusershipplaces,usershipspots,playerboard)
    players_inputted_hits = []
    gameisplaying = True
    while gameisplaying:
        playersturn=True
        while playersturn:
            while True:
                try:
                    players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9  '))
                    if players_chosen_hit in possibleusershipplaces:
                        if players_chosen_hit in players_inputted_hits:
                            while True:
                                try:
                                    players_chosen_hit = int(input('Already there! Try somewhere else!'))
                                    if players_chosen_hit not in players_inputted_hits:
                                        break
                                except ValueError:
                                    time.sleep(0.5)
                                    print("nInvalid entryn")
                                    time.sleep(0.5)
                        break
                except ValueError:
                    time.sleep(0.5)
                    print("nInvalid entryn")
                    time.sleep(0.5)
            players_inputted_hits.append(players_chosen_hit)
            playerhitai(aiboard, players_chosen_hit, aishipplaces, playerboard,usershipspots)
            playersturn = False
        aiturn = True
        while aiturn:
            aitakenmoves = aihitplayer(aiboard, playerboard, usershipspots,players_chosen_hit,aishipplaces,aitakenmoves)
            aiturn = False
        if (playerboard[usershipspots[0]] == 'x') and (playerboard[usershipspots[1]]) == 'x' and (playerboard[usershipspots[2]]) == 'x' and (playerboard[usershipspots[3]]) == 'x' and (playerboard[usershipspots[4]] == 'x'):
            print("AI WINS!")
            gameisplaying = False
        elif (aiboard[aishipplaces[0][0]] == 'x') and (aiboard[aishipplaces[0][1]] == 'x') and (aiboard[aishipplaces[1][0]] == 'x') and (aiboard[aishipplaces[1][1]] == 'x') and (aiboard[aishipplaces[1][2]] == 'x'):
            print("PLAYER WINS!")
            gameisplaying = False
    playagain()
main()

AI并不总是采取行动。这可能是因为他选择的移动CCD_ 1已经在CCD_ 2中。我列出了一个aitakenmoves列表,试图缓解这种情况,但它仍然存在。有什么帮助吗?

问题发生在函数pickX()中,您正试图使用aitakenmoves变量。有两个问题:

  1. 线路

    aitakenmoves = []
    

    每次运行该功能时,都会删除你的移动记录,因此无论AI之前采取了什么移动,都会始终选择它选择的第一个移动。

  2. aitakenmoves变量未存储在全局作用域中(这可能是您决定每次调用函数时对其进行初始化的原因),因此该变量在pickX()函数调用结束后消失。您要么想将aitakenmoves作为进行跟踪

    • A) 传递给CCD_ 10的CCD_ 9函数中的变量,CCD_。然后,您可以像在代码中的其他地方一样,通过使用多次返回,将选择从x = pickX()3传递回main()。或者
    • B) 一个真正的全局变量,在调用main()之前初始化,然后用行在pickX()中访问

      global aitakenmoves

      您可以在pickX()中直接更新。

我个人建议选择选项A,尽管实现选项B肯定更容易编程,因为干扰global可能会非常令人困惑。

附言:至少根据这里给出的代码,当玩家获胜时,人工智能仍然可以轮到自己。

编辑:如何正确实施选项A的简短演示。

def pickX(aitakenmoves):
    firsthitattempt = random.randint(1, 9)
    while firsthitattempt in aitakenmoves:
        firsthitattempt = random.randint(1, 9)
    return firsthitattempt
def aihitplayer(aiboard,playerboard, usershipspots,players_chosen_hit,aishipplaces, aitakenmoves):
    x = pickX(aitakenmoves)
    time.sleep(1)
    print("nComputer's turn.n")
    time.sleep(1)
    if x in usershipspots:
        playerboard[x] = 'x'
        drawboard(aiboard,playerboard)
        return True, x #AI makes a hit
    else:
        playerboard[x] = 'o'
        drawboard(aiboard,playerboard)
        return False, x #AI misses
def main():
    # Initialization code
    aitakenmoves = []
    while gameisplaying:
        # Game loop
        ai_hit, location = aihitplayer(aiboard, playerboard, usershipspots,players_chosen_hit,aishipplaces,aitakenmoves)
        aitakenmoves.append(location)
        # Rest of game loop

最新更新