蟒蛇井字游戏:计算机跳过它的回合

时间:2019-02-12 09:47:45

标签: python python-3.x

我在做一个井字游戏,电脑没有ai,它只是在板上选择了一个随机位置,然后将O字母放进去。我做了一个检查板上空间是否空闲的功能。

对于播放器,如果板上的空间不是空闲的,则要求播放器再输入一次,直到他们选择的空间可用为止。效果很好

但是,如果计算机随机选择一个已填补的职位,它只是不添加任何内容,并且玩家在没有补偿物在自由空间上移动的情况下转身。

tl; dr:我希望计算机进行随机输入,但要验证输入是否在空白处,这没有帮助吗?

def spacefree(board,pos): #checking if the space on board is free
    if board[pos] == ' ':
        return True
    else:
        return False

def playermove(board): #the function that checks if the players move is free that works
    pos=' '
    while pos not in '1,2,3,4,5,6,7,8,9'.split(",") or spacefree(board, int(pos)) is False:
        print('Enter your next move (1-9)')
        pos=input()
    return int(pos)

def computermove(board): #funtion that checks if the space onn the board is free for the computer that doesnt work
    pos = random.randint(0, 9)
    while spacefree(board, pos) is False:
        pos=random.randint(0, 9)
    return int(pos)

2 个答案:

答案 0 :(得分:1)

一种简单的方法:使用 random.shuffe(range(9))代替random.randint(0,9)

random.shuffle()将为您提供随机排列的列表

您可以一一检查清单中随机产生的位置。

答案 1 :(得分:0)

import random
board = { #Initialize board
    1: " ",
    2: " ",
    3: " ",
    4: " ",
    5: " ",
    6: " ",
    7: " ", 
    8: " ", 
    9:" ",
    }

def boardNewTurn(board, pos, p): #This function will detect free postion and insert input on it as well
    if board[pos] == " ":
         if p == "B":
            board[pos] = "0"
        else:
            board[pos] = "X"     
        return {"status": "Done", "board": board}
    else:
        return {"status": "Already Occupied", "board": board}

def robo_chance(board): #This is helping funtion when machine plays

    chk = 0
    while True:
        if chk == 1:
            break
        else:
            pos = random.randint(1,9)
            robo = boardNewTurn(board, pos, "B")
            print(robo["status"])
            if(robo["status"] == "Done"):
                chk = 1

def usr_chance(board, usr): #This is helping funtion when user plays

    chk = 0
    while True:
        if chk == 1:
            break
        else:
            robo = boardNewTurn(board, usr, "U")
            print(robo["status"])
            if(robo["status"] == "Done"):
                chk = 1
            else:
                usr = int(input("Enter Again:-"))    

for i in range(9): #Loop for 9 chances..
    if i % 2 == 0: #User's chance when this condition fullfills
        usr = int(input("Enter:-"))
        usr_chance(board, usr)
    else:
        robo_chance(board)
    # Here you can give function to calculate winning after each iteration.
print(board)

#I do not make a logic for win or loss