繁体   English   中英

更新:网格 PYTHON

[英]UPDATE: Mesh grid PYTHON

我正在处理一个网格,当您输入指定的数字时,该网格的光标会移动。 我能够让光标移动,我遇到的唯一问题是我希望它在光标移动时打印出更新坐标的位置(例如,如果光标向下移动一个块,新位置应该为 (0,-1))。 这就是输出的样子

x = y = 0
size = int(input('Enter grid size: '))
print(f'Current location: ({x},{y})')

def show_grid(x, y):
    for i in range(size):
        for j in range(size):
            if i == y and j == x:
                print('+', end=' ')
            else:
                print('.', end=' ')
        print()
show_grid(x,y)

def show_menu():
    print('-- Navigation --')
    print('2 : Down')
    print('8 : Up')
    print('6 : Right')
    print('4 : Left')
    print('5 : Reset')
    print('0 : EXIT')
    return 0
show_menu()

choice = int(input('Enter an option: '))            ####current location not updating
def move(x, y, choice):
    if choice == 2:     # down
        show_grid(x, y+1)
    elif choice == 8:   # up
        show_grid(x, y-1)
    elif choice == 4:   # left
        show_grid(x-1, y)
    elif choice == 6:   # right
        show_grid(x+1, y)
    elif choice == 5:   # reset to (0,0)
        show_grid(x, y)
    elif choice == 1:
        print(choice, 'Not a valid input. Try again.')
        show_grid(x, y)
    elif choice == 3:
        print(choice, 'Not a valid input. Try again.')
        show_grid(x, y)
    elif choice == 7:
        print(choice, 'Not a valid input. Try again.')
        show_grid(x, y)
    elif choice == 9:
        print(choice, 'Not a valid input. Try again.')
        show_grid(x, y)
move(x, y, choice)



#main program
while True:
    choice = show_menu()
    if choice == 0:
        print(f'Current location: ({x},{y})')
        break
    else:
        x,y = move(x,y,choice)
    print(f'Current location: ({x},{y})')
    if 0 <= x < size and 0 <= y < size:  # inside the board
        print(f'Current location: ({x},{y})')
    else:  # outside the board
        print('The new location is off the board.')
        break
    print('Exit the program')

move()定义中,在到达调用show_grid()的部分之前,您正在使用return (即退出函数show_grid()

编辑:而不是返回,只需将 x, y 设置为它们需要的任何值。 此外,我还注意到另一件事可能会给您带来问题。 您使用option来决定下一步做什么, option = show_menu() 但是您定义show_menu() ,它总是返回 0。为了让options包含用户的输入,您应该更改show_menu()的定义方式,或者更改分配option的方式。

OP 更新后编辑:以下是我看到的问题

  1. 在您的函数show_menu() :您从未要求用户提供任何输入。 你总是返回0
  2. 在您的函数move()xy未更新。 您将更新后的xy传递给show_grid() ,但之后它们不会被使用。
  3. 如果choice == 0您当前会break #main program

要解决我上面提到的每个问题,您必须执行以下操作:

  1. 在您的函数show_menu() :请求用户输入并返回它而不是 0。
  2. 返回您当前传递给show_grid()xy的新值。
  3. 删除break 如果您在没有先修复 #1 的情况下执行此操作,您最终将陷入无限循环 - 但如果您先修复 #1,它将等待用户输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM