[英]Why am I getting a “String indices must be integers” error when I am indicing a dictionary?
I am trying to code a python console game framework.我正在尝试编写 python 控制台游戏框架。 How I have designed it, there is a dictionary called game_state which is updated by a function passed into the loop function.我是如何设计它的,有一个名为 game_state 的字典,它由传递到循环 function 的 function 更新。 After one iteration of the loop, it gives the error "String indices must be integers."在循环的一次迭代之后,它给出了错误“字符串索引必须是整数”。 The stack trace shows that the error is occuring at the line if game_state["running"] == false
.堆栈跟踪显示if game_state["running"] == false
行发生错误。 When printing out game_state, it seems to be an empty string.打印出 game_state 时,它似乎是一个空字符串。 Why is this happening, and what can I do to fix it?为什么会发生这种情况,我能做些什么来解决它?
def run_loop(calculate, draw, initial_state):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin)
game_state = initial_state
with raw(sys.stdin):
with nonblocking(sys.stdin):
try:
while True:
try:
c = sys.stdin.read(1)
game_state = calculate(c, game_state)
print_map(draw(game_state))
if game_state["running"] == False:
break
except IOError:
print('not ready')
time.sleep(.1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def game(state, press):
mut_state = state
if press == "q":
mut_state["running"] = False
return mut_state
def display(game_state):
return [["Yay!"]]
run_loop(game, display, {"running": True})
The answer was right in front of me.答案就在我面前。 I was passing in the input first, meaning that empty input was overwriting the game state.我首先传入了输入,这意味着空输入覆盖了游戏 state。 It should have been calculate(game_state, c)
.它应该是calculate(game_state, c)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.