Python:Hangmangame IndexError:列表赋值索引超出范围

时间:2011-06-12 18:27:27

标签: python arrays

我正在看python,但我似乎遇到了一个问题:

我有两个数组,一个是字符串的每个字母,我从一个文件中随机获取,另一个数组用“_”填充用户需要找到的单词中的每个字母。

然而,似乎我的while循环没有结束,即使找到了这个单词,它仍然继续。

有人能找到我的错吗?

这是我在python中的第一个代码,我来自java所以提示和关于如何更好地编写代码也很感激:)

感谢。

我的代码:

'''
Created on 12-jun.-2011

@author: k3r3nks7
'''
import random


class Hangman(object): 

    def _init_(self):
        self.fileInput()
        self.printStuff()

    def fileInput(self): 
        wordList = open('wordlist')

        woordenArray=[]

        for line in wordList:
            woordenArray.append(line)

        i = random.randrange(0,len(woordenArray))

        self.randomWoord = woordenArray[i]



    def printStuff(self):
        print 'I want to play a game\n\n'
        print 'Hangman spelen ? (y/n)\n'
        stringEval = raw_input()
        self.checkToPlay(stringEval)



    def checkToPlay(self,woord):
        if woord == 'y':
            print '#####################'
            print '#let the game begin!#'
            print '#####################'
            self.iwanttoplayagame()

        elif woord == 'n':
            print 'have a nice day'
            exit()
        else:
            print 'Your answer was not correct, please answer a correct parameter,\n resistance is futile, \n We are Borg sheep and .... \n ... oh look fresh gras \n'
            self.printStuff()

    def iwanttoplayagame(self):
        incorrectGuesses = 0
        self.correctArray = []
        for char in self.randomWoord:
            self.correctArray.append('_')
        test=""

        while(incorrectGuesses <= 6 or self.correctArray != self.randomWoord ):
            print 'u raadde al : '+test.join(self.correctArray)
            print "Geef is een letter \n"
            letterInput = raw_input()
            _c=0


            if letterInput in self.randomWoord: 


                for letter in self.randomWoord:

                    if(letter == letterInput):
                        self.moveChar(letter,_c)
                    _c+=1    
            else:
                incorrectGuesses+=1
                self.display_figure(incorrectGuesses)



    def moveChar(self,letter,c):
        self.correctArray[c] = letter


    def display_figure(self,bad_guesses):
        graphics = [
        """
            +--------+
             |
             |
             |
             |
             |
             |
         ====================
        """,
        """
            +-------
            |      o
            |
            |
            |
            |
        ====================
        """,
        """
            +-------
            |      o
            |   ---+---
            |
            |
            |
        ======================
        """,
        """
            +-------
            |       o
            |    ---+---
            |       |
            |    
            |  
            |   
        =====================
        """,
        """
            +-------
            |  
            |       o
            |    ---+
            |       |
            |      / 
            |     /   
            |
            |
            |
            |
        =====================
        """,
        """
            +-------
            |        o
            |     ---+---
                     |
            |       / 
            |      /   
            |     /     
            |     
        =====================
        """,
          """
            +-------
            |        o
            |     ---+---
                     |
            |       / \
            |      /   \  
            |     /     \    
            |     
        =====================
        """
    ,]

        if(bad_guesses== 7):
            print "you lost the game. The correct answer was : "+self.randomWoord
            print "\n Do you want to play again ?"
            inputS = raw_input()
            self.checkToPlay(inputS)
        print graphics[bad_guesses]

f = Hangman()
f._init_()

2 个答案:

答案 0 :(得分:3)

在这一行:

while(incorrectGuesses <= 6 or self.correctArray != self.randomWoord ):

or应为and。此外,correctArray是一个列表,但randomWord是一个字符串,因此它们永远不会相等。括号也是不必要的。试试这个:

while incorrectGuesses <= 6 and ''.join(self.correctArray) != self.randomWoord :

_init_应该是__init__,那么您就不必明确地调用它。

从wordlist中读取的行将附加\n。使用strip()删除它,或correctArray一个字符太长。

for line in wordList:
    woordenArray.append(line.strip())

答案 1 :(得分:1)

首先在fileInput()方法中,从文件中读取的单词最后会有'\ n'(我怀疑这就是你的循环没有结束的原因)来解决这个问题你应该这样做:

for line in wordList:
     woordenArray.append(line.strip())

如果您忘记关闭文件'wordlist',我建议您使用with statement可以理解的列表来填充wordList,如下所示:

with open('wordlist') as wordList: 
    woordenArray = [line.strip() for line in wordList]

我相信这个循环:

_c=0
if letterInput in self.randomWoord: 
    for letter in self.randomWoord:
        if(letter == letterInput):
            self.moveChar(letter,_c) 

可以这样写得更好:

if letterInput in self.randomWoord: 
    for i, letter in enumerate(self.randomWoord):
        if letter == letterInput:
            self.correctArray[i] = letter

这也是:

self.correctArray = []
for char in self.randomWoord:
    self.correctArray.append('_')

可以替换为:

self.correctArray = ['_'] * len(self.randomWoord)

你也写错了__init__() python _init_()你应该这样做:

class Hangman(object): 

    def __init__(self):
        self.fileInput()
        self.printStuff()

您不必在脚本的末尾添加f._init_()

修改

还有一个人认为我错过了while循环条件应该写成:

while incorrectGuesses <= 6 and self.correctArray != list(self.randomWoord):
    ...

在我们比较self.randomWoord这是一个字符串与self.correctArray这是一个列表之前,它应该是和不是或在条件中。

希望这有用:)