为什么我的程序匹配错误的值?

时间:2016-11-15 21:29:07

标签: python for-loop

我正在制作一艘战舰游戏。我无法理解为什么当您在 n 不同位置重叠船只时,我的程序会要求您输入不同的起始位置 n 次。

def make_ships(name, length, position, orientation):
    ships[name] = {"length": length, "Coordinates": {}}
    x = ord(position[:1])
    y = int(position[1:])
    coords = {}
    if orientation.lower() == "y":
        for i in range(0, length):
            place = ''.join([chr(x), str(y)])
            coords[place] = "-"
            x = x + 1
    elif orientation.lower() == "n":
        for i in range(0, length):
            place = ''.join([chr(x), str(y)])
            coords[place] = "|"
            y = y + 1
    print("Coordinates of incoming ship: {}".format(list(coords.keys())))
    names = []
    for item in ships:
        names.append(item)
        # a.append(list(self.ships[item]["Coordinates"].keys()))
    for var in names:
        for item in coords.keys():
            if item in list(ships[var]["Coordinates"].keys()) and ships[name] != ships[var]:
                print("Coordinates of {}: {}".format(var, list(ships[var]["Coordinates"].keys())))
                new_position = input("There is an overlap at {}. Please enter a different starting position: ".format(item)).replace(" ","")
                new_orientation = input("Is it horizontal? (Y/N): ").replace(" ","")
                make_ships(name, length, new_position, new_orientation)
    ships[name]["Coordinates"] = coords

ships = {}
ships["Aircraft Carrier"] = {}
ships["Aircraft Carrier"] = {"length": 5, "Coordinates": {'a1':'|', 'a2':'|', 'a3':'|', 'a4':'|', 'a5':'|'}}
make_ships("Battleship", 4, 'a1', 'n')

原始呼叫中的战舰与4个位置的现有航空母舰重叠。 该程序会要求您输入新的位置和方向。 如果您选择 b1 ,程序会声明重叠并显示运营商的坐标 a1-a5 ,这显然 b1-b4 中重叠一艘船。

1 个答案:

答案 0 :(得分:2)

<强>问题

您的错误是使用递归调用 make_ships ,而不是简单的迭代( while循环)。如果第一个条目因空格 a4 而失败,您将获得新船的信息并添加得很好。但是,您将从递归调用返回到第一个调用,您仍处于检查循环中。迭代到a-column检查中的下一个空格,发现原始调用的 a1 也匹配(如果你很顽固,你会&#l; ll得到这四次,每次碰撞原始战舰一次。)

<强> REPAIR

干净的方法是将这个过程替换为&#34;读取直到好的&#34; while循环。伪代码是:

获得第一个输入    虽然输入是不可接受的        获得替代输入

便宜的方法是在递归调用后简单地输入 return 。我的代码,包括我的调试工具,如下所示。当我对此进行测试时,我将替换战舰放在q7 :-)处,这显然表明这个问题与船只触碰无关。

def make_ships(name, length, position, orientation):
    print ("===> ENTER make_ships", name, length, position, orientation)
    ships[name] = {"length": length, "Coordinates": {}}
    x = ord(position[:1])
    y = int(position[1:])
    coords = {}

    if orientation.lower() == "y":
        for i in range(0, length):
            place = ''.join([chr(x), str(y)])
            coords[place] = "-"
            x = x + 1
    elif orientation.lower() == "n":
        for i in range(0, length):
            place = ''.join([chr(x), str(y)])
            coords[place] = "|"
            y = y + 1
    print("Coordinates of incoming ship: {}".format(list(coords.keys())))

    # Validating for ship overlap
    names = []
    for item in ships:
        names.append(item)
        # a.append(list(self.ships[item]["Coordinates"].keys()))
    for var in names:
        # print ("coords.keys=", coords.keys())
        for item in coords.keys():
            print ("\ncoords.keys=", coords.keys())
            print ("var=", var, "\tname=", name, "\titem=", item)
            print (ships[var]["Coordinates"].keys())
            if item in list(ships[var]["Coordinates"].keys()) and ships[name] != ships[var]:
                print("Coordinates of {}: {}".format(var, list(ships[var]["Coordinates"].keys())))
                new_position = input("There is an overlap at {}. Please enter a different starting position: ".format(item)).replace(" ","")
                new_orientation = input("Is it horizontal? (Y/N): ").replace(" ","")
                make_ships(name, length, new_position, new_orientation)
                return

    ships[name]["Coordinates"] = coords

    print ("===> EXIT make_ships", coords)


ships = {}
ships["Aircraft Carrier"] = {}
ships["Aircraft Carrier"] = {"length": 5, "Coordinates": {'a1':'|', 'a2':'|', 'a3':'|', 'a4':'|', 'a5':'|'}}

make_ships("Battleship", 4, 'a1', 'n')