【问题标题】:Python recursion error, but not using recursionPython递归错误,但不使用递归
【发布时间】:2013-01-13 20:33:14
【问题描述】:

我没有在我的代码中使用递归,所以我不明白为什么我会收到关于递归的错误。 ..................................................... .........................................

代码是:

from os import system
from time import sleep
import msvcrt 

player_location = [0, 0]
player_dir = [0, 0]
width = int(raw_input('Width:'))
height = int(raw_input('Height:'))

def get_input():
    if msvcrt.kbhit():
        return msvcrt.getch()
    else:
        return ''

def update_screen():
    global player_location
    system('cls')
    for i in range(0, (height-1)):
        if i == player_location[0]:
            print (' ' * (player_location[1] - 1)) + 'X' + (' '*(width*2 - player_location[1] - 1)) + '|'
        else:
            print (' ' * width * 2) + '|'
    print ('-' * width * 2) + '+'

 def get_input():
    global player_dir
    player_dir = [0, 0]
    inp = get_input()
    if inp == 'q':
        exit()
    elif inp == 'w':
        player_dir[0] = -1
    elif inp == 's':
        player_dir[0] = 1
    elif inp == 'd':
        player_dir[1] = 1
    elif inp == 'a':
        player_dir[1] = -1

def actions():
    global player_dir, player_location
    player_location[0] += player_dir[0]
    player_location[1] += player_dir[1]

if __name__ == '__main__':
    while True:
        update_screen()
        sleep(10)
        get_input()
        actions()

错误是这样的:

Traceback (most recent call last):

然后这行很多次:

  File "C:\Python\txtpltfrmr.py", line 29, in get_input
    inp = get_input()

然后这一行:

RuntimeError: maximum recursion depth exceeded

【问题讨论】:

  • 您正在使用递归,只是您没有意识到。您的 get_input 函数调用自身。
  • "in get_input: inp = get_input()" 应该是你的暗示,也许问题是 get_input 调用 get_input。
  • 您是否查看了 get_input 中的第 29 行?如果只有所有错误消息都能如此准确地指出错误。

标签: python recursion msvcrt


【解决方案1】:
def get_input():
    if msvcrt.kbhit():
        return msvcrt.getch()
    else:
        return ''

def get_input():
    global player_dir
    player_dir = [0, 0]
    inp = get_input() # INFINITE RECURSION, CALLS ITSELF

你的问题。您有两个名为 get_input 的函数具有匹配的签名。将其中一个重命名,可能是第一个重命名为 get_character

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多