[英]Checking if entered coordinates are valid
因此,我编写了一个python函数,用于测试用户以[column][row]
-> eg格式输入的输入。 第2列第3列为“ 23”。我可以更改电路板的大小,但是我不太确定实现检查的最佳方法是确保程序不会在这些条件下崩溃输入,而是提示用户再次输入坐标:
这是我目前的python检查:
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
。
这样的事情对您有用吗?
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."
我将使用两种方法。 一种获得输入,另一种进行检查:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.