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 = [[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "],[" "," "," "," "," "," "]]
解决方案
改善游戏的几点:
- 正如评论和其他答案所提到的,设置值时一定要保持在数组\列表长度中。使用
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:
推荐阅读
- node.js - 在 Koa 中发送对象流作为响应
- hibernate - 数据库中唯一键的重复条目
- python - 如何跳过忽略错误并测试另一个条件python
- excel - Excel堆积条形图所需的数据结构
- mysql - 当我使用完全相同的查询定位不同的列时,查询不起作用
- python - 在这种情况下,这个 Python 的列表值赋值是如何工作的?
- node.js - 如何修复'错误:找不到模块'supertest''
- python - 如何修复opencv/modules/objdetect/src/cascadedetect.cpp:1698:错误:(-215:断言失败)!函数'detectMultiScale'^中的empty()?
- batch-file - 执行 bat 文件后获取不需要的文件
- r - R使用嵌套的for循环尾部扩展和处理数据