即使位置被占用,代码也会通过并运行下一行。。抽搐

2024-04-26 00:12:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我用我的逻辑来做这个游戏。不过我觉得代码很长,谁能帮我缩短代码,帮我理解怎么写?我应该创建函数吗?另外,当这个地方被占用时,它应该显示消息“place is already taked”,这只是第一次发生,第二次当我输入相同的数字时,它就通过了。代码如下:

board = [" " for i in range(9)]

def print_board():

    row1="|{}|{}|{}|".format(board[0],board[1],board[2])
    row2="|{}|{}|{}|".format(board[3],board[4],board[5])
    row3="|{}|{}|{}|".format(board[6],board[7],board[8])

    print()
    print(row1)
    print(row2)
    print(row3)
    print()

while True:

    print_board()

    choice=int(input("enter your choice, player 1").strip())

    if board[choice-1]==" ":
        board[choice-1]= "X"
        print_board()

    else:

        print("space is taken, try again")
        choice=int(input("enter your choice, player 1").strip())
        if board[choice-1]==" ": 
            board[choice-1]= "X"
            print_board() 


    choice=int(input("enter your choice, player 2").strip())

    if board[choice-1]==" ":
        board[choice-1]= "0"
    else:
        print("space is taken")
        choice=int(input("enter your choice, player 2").strip())
        if board[choice-1]==" ":

            board[choice-1]= "X"
            print_board()

Tags: 代码boardformatinputyourifisint
1条回答
网友
1楼 · 发布于 2024-04-26 00:12:49
board = [" " for i in range(9)]

def print_board():

    row1="|{}|{}|{}|".format(board[0],board[1],board[2])
    row2="|{}|{}|{}|".format(board[3],board[4],board[5])
    row3="|{}|{}|{}|".format(board[6],board[7],board[8])

    print("\n" + row1 + "\n" + row2 + "\n" + row3 + "\n")

def verify(numPlayer):
    choice=int(input("enter your choice, player " + str(numPlayer)).strip())
    while board[choice-1]!=" ": #while the coice of user is not a empty slot. You hadn't verify his second choice and he could put in another occupied slot
        print("space is taken, try again")
        choice=int(input("enter your choice, player " + str(numPlayer)).strip())
        #You have to verify also if there is an empty slot

     if numPlayer ==1:
         board[choice-1]= "X"
     else: 
         board[choice-1]= "0"


while True:
   print_board()
    verify(1)
    print_board()
    verify(2)
    print_board()

相关问题 更多 >