提问者:小点点

如何避免在这个程序中获得索引错误?[关闭]


我正在终端上做一个游戏,我刚刚知道如何显示角色的位置。唯一的问题是如何避免这个索引器?

以下是我的计划(或我想要实现的目标所需要的):

import time, random, os

def replaceChar(char, index, text_):
    text = [i for i in text_]

    text[index] = char

    result = ''
    for i in text:
        result += i
    return result

def read(file):
    file = open(file)
    return [line[:len(line)-1] for line in file.readlines()]

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

def randomString(length=12,\
 charSet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'):
    import random
    string = ''
    for i in range(length):
        char = charSet[random.randint(0, len(charSet)-1)]
        string += char

    return string

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class Display:

    class Window:
        def __init__(self,):
            self.terminalWidth, self.terminalHeight = 0, 0

    def __init__(self,):
        self.Window = Display.Window()
        self.testfile = '/file/of/the/room/txt/file/dir/here/r1.txt'
        self.lines = []

    def checkWindow(self,):
        self.Window.terminalWidth, self.Window.terminalHeight = getTerminalSize()
        return not (int(self.Window.terminalWidth) < 80 or int(self.Window.terminalHeight) < 28)

    def draw(self,):
        os.system('clear')

        stats = {'HP'    : Game.HP}
        statlines = ['HP:     {}'.format(stats['HP'])]
        content = read(self.testfile)

        for i in content:
            content[content.index(i)] = '     '+i

        content[Game.posY] = replaceChar('@', Game.posX+5, content[Game.posY]) #this is the line i need help with

        for f in statlines:
            content.append('     '+f)
            for i in range(70-len(f)):
                content[len(content)-1]+=' '
        else:
            content.insert(0, '     lol    {0}x{1}    POS: {2},{3}'.format(self.Window.terminalWidth,\
            self.Window.terminalHeight, Game.posX, Game.posY))

        for line in content:
            print(line)

    def drawTest(self,):
        stats = {'HP': Game.HP}
        statlines = ['HP:     {}'.format(stats['HP'])]
        content = fe.read(self.testfile)

        for i in content:
            content[content.index(i)] = '     '+i

        for f in statlines:
            content.append('     '+f)
            for i in range(70-len(f)):
                content[len(content)-1]+=' '
        else:
            content.insert(0, '     '+__version__+'    '+str(self.Window.terminalWidth)+'x'+\
            str(self.Window.terminalHeight))

        for line in content:
            print(line)

class Game:
    class Rooms:
        def __init__(self,):
            self.directory = os.path.dirname(__file__)+'/Rooms/'
            self.rooms = []
            self.currentRoom = 'r1'

        def getRooms(self,):
            files = []

    def __init__(self,):
        self.devtools  = False
        self.XP        = 0
        self.nextLevel = 100
        self.level     = 1
        self.maxHP     = 20
        self.HP        = self.maxHP
        self.maxX, self.maxY = 38, 8
        self.posX, self.posY = random.randint(self.maxX*-1, self.maxX),\
                               random.randint(self.maxY*-1, self.maxY)
        self.keys = {'w': 'up',
                     's': 'down',
                     'a': 'left',
                     'd': 'right',
                     'e': 'open inventory',
                     'q': 'use item',
                     'h': 'help'}
        self.Rooms    = Game.Rooms()

    def _action(self,):
        try:
            action = self.keys[getch()]
            self.XP += 1
        except:
            action  = ''

        if   action == 'up'   : self.posY += 1
        elif action == 'down' : self.posY -= 1
        elif action == 'left' : self.posX -= 1
        elif action == 'right': self.posX += 1

    def __call__(self,):
        Display.draw()
        self._action()


Game = Game()
Display = Display()
getch = _Getch()

if __name__ == '__main__':
    Game.Rooms.getRooms()

    while True:
        Game()
        time.sleep(0.1)

显示字符(@)的行位于第114行,内容[Game.posY]=replace eChar('@',Game.posX 5,内容[Game.posY])

我每次得到的错误是:

Traceback (most recent call last):
  File "/Users/ashton/Desktop/Atom/Python/Game/DungeonGame_.py", line 200, in <module>
    Game()
  File "/Users/ashton/Desktop/Atom/Python/Game/DungeonGame_.py", line 188, in __call__
    Display.draw()
  File "/Users/ashton/Desktop/Atom/Python/Game/DungeonGame_.py", line 114, in draw
    content[Game.posY] = replaceChar('@', Game.posX+5, content[Game.posY]) #this is the line i need help with
  File "/Users/ashton/Desktop/Atom/Python/Game/DungeonGame_.py", line 6, in replaceChar
    text[index] = char
IndexError: list assignment index out of range

注意:对于第97行,只需做一个标记。txt文件,并将其放入包含该文件的文件夹中的新文件夹中。py文件。将文件路径粘贴到第97行(self.testfile='/file/of/the/room/txt/file/dir/here/r1.txt')


共1个答案

匿名用户

因为您无法调试,所以在第316行中有一个猜测,您可以在最小-最大范围内随机初始化coords

self.posX, self.posY = random.randint(self.maxX*-1, self.maxX),\
                               random.randint(self.maxY*-1, self.maxY)

在第163行,您调用游戏。posX 5可能超出生成坐标的范围