[英]Why am I getting a “String indices must be integers” error when I am indicing a dictionary?
我正在嘗試編寫 python 控制台游戲框架。 我是如何設計它的,有一個名為 game_state 的字典,它由傳遞到循環 function 的 function 更新。 在循環的一次迭代之后,它給出了錯誤“字符串索引必須是整數”。 堆棧跟蹤顯示if game_state["running"] == false
行發生錯誤。 打印出 game_state 時,它似乎是一個空字符串。 為什么會發生這種情況,我能做些什么來解決它?
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})
答案就在我面前。 我首先傳入了輸入,這意味着空輸入覆蓋了游戲 state。 它應該是calculate(game_state, c)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.