2016-05-12 65 views
0

所以我寫了一個python函數,用於測試用戶輸入的輸入格式爲[column][row] - > eg。第2列第3行的「23」。我可以更改電路板的大小,但我不太確定實施檢查的最佳方式是確保程序不會在這些輸入,但相反,只是提示用戶再次輸入座標:檢查輸入的座標是否有效

  1. 用戶輸入一個空格(按回車鍵)。
  2. 用戶輸入行或列索引範圍之外的座標。
  3. 用戶輸入一個字母或數字以外的任何其他字符。

這是我的時刻蟒蛇檢查:

def checkIfMoveIsValid(Board, Move): 
    Row = Move % 10 
    Column = Move // 10 
    MoveIsValid = False 
    if Board[Row][Column] == " ": 
    MoveIsValid = True 
    return MoveIsValid 

我試圖實現這一點 - >

inp = input() 
    if inp and inp.isdigit(): 
    Coordinates = int(inp) 
    else: 
    return 0 
    return Coordinates 

但對於這個只檢查沒有協調和正確的輸入任何東西分開。但它不檢查座標是否在範圍內,因此,如果輸入了超出範圍的座標,則程序崩潰,並且它說:list index out of range

回答

-1

這樣的事情會對你有用嗎?

def checkIfMoveIsValid(Board, Move): 
    MoveIsValid = False 
    while MoveIsValid == False: 
     inp = raw_input("coordinates: ") 
     if inp.isdigit() and len(inp) == 2: 
      x_coord = int(inp[0]) 
      y_coord = int(inp[1]) 
      MoveIsValid = True 
      return x_coord, y_coord 
     else: 
      print "enter the coordinates again please." 
-1

我會用兩種方法。一個得到輸入和一個來檢查它:

def check_input(Board,input): 
    #I assume the Board has dimensions (Board.size) x (Board.size) 
    #I also assume you can get the dimensions of the board 
    return input in range(11,Board.size**2+1) 

def get_input(): 
    valid = False 
    while valid is False: 
     position = int(raw_input("Enter a valid board position: ")) 
     valid = check_input(Board,position) 
    return position