总是碰到异常

2024-06-28 11:40:48 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在做一些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 = [[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "]]

Tags: 代码游戏ifdefconnectcolumn数字整数
2条回答

currentField只有6列,范围检查为11,因此对于currentField大小,检查范围直到5(包括零索引,因此总长度将为6)。 类似地currentField有7行,但是检查了13行,应该检查6行

for i in range(5):
if columnSelect >= 0 and columnSelect <= 13: 

或者更新currentField以匹配12x14的大小

改善游戏的几点措施:

  • 正如前面提到的注释和其他答案,在设置值时,请确保保持数组\列表长度。使用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:

相关问题 更多 >