【问题标题】:My function isn't working and I don't know why. Python我的功能不起作用,我不知道为什么。 Python
【发布时间】:2021-01-04 18:29:51
【问题描述】:

所以我有一个有 9 个位置和 6 个棋子的棋盘,3 个 [X] 和 3 个 [ ](你也可以考虑一个棋子“[ ]”,但它代表一个空位置)。玩家可以选择将棋子移动到任何他想要的位置到他附近的位置。在下面的棋盘中,“X”(这就是我们表示棋子的方式,就像棋盘上的棋子一样,但没有 [])必须移动,但他无处可去。我想要一个函数来查看玩家是否没有合法动作,如果是,则返回 True。这些是helping functions

#pc stands for piece, brd for board and pos for position

board = ["[X]","[X]","[X]",
         "[O]","[O]","[O]",
         "[ ]","[ ]","[ ]"]

def near_pos(pos):    #positions are represented 1-9 and this functions gives the near positions of a position
    if pos== 1:
        return (2,4,5)
    elif pos== 2:
        return (1,3,4,5,6)
    elif pos== 3:
        return (2,5,6)
    elif pos== 4:
        return (1,2,5,7,8)
    elif pos== 5:
        return (1,2,3,4,6,7,8,9)
    elif pos== 6:
        return (2,3,5,8,9)
    elif pos== 7:
        return (4,5,8)
    elif pos== 8:
        return (4,5,6,7,9)
    elif pos== 9:
        return (5,6,8)

def free_pos(brd,pos):   #you give it a board and a position and it returns True if it is free
    pos -= 1
    if brd[pos] == "[ ]":
        return True
    else:
        return False

def player_pos(brd,pc):      #It works now
    l = []
    for i in range(0,9):
        if pc == "X":
            if brd[i] == "[X]":
                l.append(i + 1)
        elif pc == "O":
            if brd[i] == "[O]":
                l.append(i + 1)
    return (* l,)

#The last function (the one that I'll write next, sorry if I caused any misunderstanding) was supposed to see if from the positions I got from player_pos, if any had a close position available. The way I thought I could do that was by seeing for each position the positions near that one, using near_pos function, and determine if there was any clear one, using free_pos.

我写的是这个,但它是错误的,我不知道如何解决它

def No_Free_Positions(brd,pc):
    if pc == "X":
        a = "O"
    if pc =="O":
        a = "X"
    for player_pos(brd,pc) in near_pos(pc):
        if Free_Pos(brd,near_pos(pc)) is False:
            return "No"
        else:
            return "Yes"

有什么问题?

【问题讨论】:

  • brd[pos] == " " 永远不会是真的。如果要匹配一个空方块,应该是brd[pos] == "[ ]"
  • 也许你不应该将[] 放在board 中,只需将XO 或空格。然后在显示板时添加括号。

标签: python python-3.x


【解决方案1】:

free_pos 函数将始终返回 false,因为这种情况: if brd[pos] == " "。这会检查给定的方格是否为空,但是程序中的空方格是 "[ ]",因此它永远不会返回 true。这是更正后的代码:

if brd[pos] == "[ ]":

【讨论】:

  • 哦,那是我在复制时出错了,对不起
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 2020-02-05
  • 2016-10-19
  • 2020-09-19
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多