多维数组的路径搜索算法

2024-09-27 09:29:59 发布

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

我正在尝试制作一个基于地下城的游戏,并且正在制作一个理论路径搜索程序,但是每当我运行这个程序时,它只会打印出我在第一个位置输入的相同坐标(理论坐标)。一般来说,我对编程有点“陌生”,所以我被卡住了

import winsound
def main():
    snd = winsound.Beep
    a = input("Enter the x value for the entrance: ")
    b = input("Enter the y value for the entrance: ")
    entrance = [a, b]

    x = input("Enter the x value for the exit: ")
    y = input("Enter the y value for the exit: ")
    a = float(a)
    b = float(b)
    x = float(x)
    y = float(y)
    exut = [x, y] #deliberatly placed exit misspelling as exit is a command
    done = False
    while done == False:
        if b > a:
            b = b - 1
        elif b < a:
            b = b + 1
        else:
            if a > x:
                a = a - 1
            elif a < x:
                a = a + 1
            else:
                done = True

    done2 = False
    while done2 == False:
        if b > y:
            b = b - 1
        elif b < y:
            b = b + 1
        else:
            snd(494, 250)
            snd(659, 400)
            print("done!")
            print(entrance)
            print(exut)
            entrance = [a, b]
            exut = [a, b]
            done2 = True

当我运行它,让我们说1代表入口的x值,2代表入口的y值,3代表出口的x值,4代表出口的y值,我得到这个结果

>>> main()
Enter the x value for the entrance: 1
Enter the y value for the entrance: 2
Enter the x value for the exit: 3
Enter the y value for the exit: 4
done!
['1', '2']
[3.0, 4.0]
>>> 

我不知道为什么会这样,所以请你帮忙,非常感谢,谢谢。你知道吗


Tags: thefalseforinputifvalueexit代表
1条回答
网友
1楼 · 发布于 2024-09-27 09:29:59

首先,您不需要转换为float,因为您只在一个步骤中移动,所以请删除以下代码:

a = float(a)
b = float(b)
x = float(x)
y = float(y)

这是不一致的,因为在转换为float之前将ab分配给entrance,但在转换之后将xy分配给exut。但是,您应该添加代码以确保只能为entranceexut输入整数值。你知道吗

在第一个循环中,您将ba进行比较,此时它应该与y进行比较(因为yb的目标值):

 while done == False:
    if b > y:       # changed a to y here
        b = b - 1
    elif b < y:     # changed a to y here too
        b = b + 1
    else:
        if a > x:
            a = a - 1
        elif a < x:
            a = a + 1
        else:
            done = True

另外,您不需要第二个循环,因为在第一个循环完成之后,ab将被设置为xy。所以你可以打印出你的值。你知道吗

打印entranceexut,但不打印ab的最终值:

print("done!")
print(entrance)
print(exut)
print(a, b)  # print out a and b. they should be equal to exut

如果您想查看pathfinder的进度,可以将print(a, b)添加到pathfinding循环中:

 while done == False:
    print(a, b)
    if b > y:       # changed a to y here
        b = b - 1
    elif b < y:     # changed a to y here too
        b = b + 1
    else:
        if a > x:
            a = a - 1
        elif a < x:
            a = a + 1
        else:
            done = True

相关问题 更多 >

    热门问题