首页 > 解决方案 > 总是遇到异常

问题描述

目前正在做一些 python 的事情,我不能使用任何导入。

我正在制作一个 connect 4 游戏,出于某种原因,我一直在下面的代码中遇到异常。我已经将一些东西改为整数而不是它们的变量,这样你就可以看到我输入的内容。无论输入什么数字,我总是点击“无效列”

def play():
    while (True):
        try:
            drawfield(currentField)
            print(f"Players turn: {Player}")
            columnSelect = int(input("Select your column: "))
            if columnSelect >= 0 and columnSelect <= 13:
                for i in range(11):
                    if currentField[columnSelect][i] != " ":
                        locate = i - 1
                mark(columnSelect, locate)
            else:
                raise print("outside board")
            break
        except:
            print("Invalid column")
             except:
                 print("Invalid column")

我得到的错误是索引超出范围。名单是:

currentField = [[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "]]

标签: python

解决方案


改善游戏的几点:

  • 正如评论和其他答案所提到的,设置值时一定要保持在数组\列表长度中。使用len(mylist)而不是硬编码长度很有帮助。
  • 除非您可以从错误中恢复(或记录错误),否则 Try\Except 并不是真正有用。在这种情况下,只要让错误发生,您就可以看到问题。
  • 当检查板上的空地时,从底部开始,找到第一个空单元格。
  • 考虑到一列可能已满,因此无法添加新部分。

我使用此代码进行测试:

currentField = [
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "],
   [" "," "," "," "," "," "]]
   
def drawfield():
   for x in range(len(currentField[0])):
      for y in range(len(currentField)):
         print("|" + currentField[y][x], end="")
      print("|")
      
def mark(x, y, p): 
   currentField[x][y] = p  # update field with player

def play():
    Player = 'X'  # player is X or O
    while (True):
        drawfield()
        print(f"Players turn: {Player}")
        columnSelect = int(input("Select your column: "))
        if columnSelect >= 0 and columnSelect <= 6:  # can also use len(currentField)
            locate = 0
            for i in range(5,-1,-1):  # start from bottom, find first empty cell
                if currentField[columnSelect][i] == " ":
                    locate = i
                    mark(columnSelect, locate, Player) # update field
                    break # found cell, loop is done
            else:  # no empty cells
               print("Column is full")
            Player = 'X' if Player == 'O' else 'O'  # swap players
        else:
            print("outside board")              
play()

播放时输出

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |O|X| | | |
| | |X|O|X| | |
| | |O|X|O| |X|
Players turn: O
Select your column:

推荐阅读