2016-12-07 65 views
0

我想出了以下代碼,它創建了一個網格並允許用戶四處移動。不允許玩家在2D網格外移動Python 3

choice_size = 8 
board = [] 
x = choice_size 
y = x 
for row in range(0,x): 
    board.append(["."]*y) 

def print_board(board): 
    for row in board: 
     print(" ".join(row)) 
x = choice_size - 1 
y = 0 
while True: 
    board[x][y] = "P" 
    print_board(board) 
    board[x][y] = "." 
    right = ["right", "Right", "R", "r"] 
    left = ["Left", "left", "L", "l"] 
    up = ["Up", "up", "U", "u"] 
    down = ["Down", "down", "D", "d"] 
    direction_choice = input("Which direction would you like to move vertically (Up/Down)?") 
    if direction_choice.strip() in up: 
     movement_value = int(input("How far do you want to move up?")) 
     x = x - movement_value 
    elif direction_choice.strip() in down: 
     movement_value = int(input("How far do you want to move down?")) 
     x = x + movement_value 
    else: 
     print("Please ensure that you have chosen a valid option") 
    direction_choice = input("Which direction would you like to move horizontally (Left/Right)?") 
    if direction_choice.strip() in right: 
     movement_value = int(input("How far do you want to move right?")) 
     y = y + movement_value 
    elif direction_choice.strip() in left: 
     movement_value = int(input("How far do you want to move left?")) 
     y = y - movement_value 
    else: 
     print("Please ensure that you have chosen a valid option") 

當我輸入一個移動將使我走出網格的底部時,出現錯誤。而且我仍然可以從板子的一側移到另一側(例如,如果我從板子的邊緣向左移動,我將最終位於板子的右側)。 我嘗試過使用Try/Except IndexError,但找不到任何解決方案。

回答

0

想想發現列表中的「板」中的X和Y座標的位置,然後比較這對你的板子

+1

因此,Y座標的大小將是子表的「板」中的位置而X座標是該子列表內的位置? –