输入无效坐标时防止程序崩溃

时间:2016-03-29 18:57:37

标签: python

以下是代码的一些相关部分。如果用户输入超出范围的错误坐标,甚至其他字符/符号,程序会提示他们再次输入,您将如何修复它?

以下是该计划的相关部分:

导入随机

def SetUpGameBoard(Board, Boardsize):
  for Row in range(1, BoardSize + 1):
    for Column in range(1, BoardSize + 1):
      if (Row == (BoardSize + 1) // 2 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2 + 1):
        Board[Row][Column] = "C"
      elif (Row == (BoardSize + 1) // 2 + 1 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2):
        Board[Row][Column] = "H"
      else:
        Board[Row][Column] = " "

def ChangeBoardSize():
  BoardSize = int(input("Enter a board size (between 4 and 9): "))
  while not(BoardSize >= 4 and BoardSize <= 9):
    BoardSize = int(input("Enter a board size (between 4 and 9): "))
  return BoardSize

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

def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
  Row = Move % 10
  Column = Move // 10
  if HumanPlayersTurn:
    Board[Row][Column] = "H"
  else:
    Board[Row][Column] = "C"
  FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0)
  FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0)
  FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1)
  FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1)

非常感谢所有的帮助。如果您想查看并运行它,这是完整的代码:

http://www.writeurl.com/text/mpt643e0ryn96l0m8zhc/tpcx0mbjc8hdqo2zizwm/ettx0pq62ufshh3y2ays

1 个答案:

答案 0 :(得分:0)

好吧,你可能会遇到试图将字符串转换为整数的ValueError。 由于ChangeBoardSize是您处理用户输入的唯一地方,因此解决方案可能是:

def ChangeBoardSize():
    try:
        BoardSize = int(input("Enter a board size (between 4 and 9): "))
        assert 4 <= BoardSize <= 9
        return BoardSize
    except:  # ValueError, AssertionError
        ChangeBoardSize()

而且,正如评论中所指出的,你应该坚持使用Python编码约定(例如函数,变量的驼峰大小写)