Skip to main content
 首页 » 编程设计

python之刽子手游戏 : Words have unwanted character at the end

2025年05月04日12jiqing9006

这是我的刽子手游戏代码的一部分。它用于所有四个困难,但是当它用于我的“疯狂”困难(使用单词文件中的单词)时,它会在单词的末尾添加一个额外的符号,这意味着您无法赢得比赛。它对 .txt 文件中的每个单词执行此操作。 在 python 窗口中使用数组时,此代码有效。

def insane(): 
    global score   
    print ("This words may contain an apostrophe. \nStart guessing...") 
 
    time.sleep(0.5) 
 
    word = random.choice(words).lower() 
    print (word) 
    guesses = '' 
    fails = 0 
    while fails >= 0 and fails < 10:  #try to fix this          
        failed = 0                 
        for char in word:       
            if char in guesses:     
                print (char,)     
 
            else: 
                print ("_"),      
                failed += 1     
        if failed == 0:         
            print ("\nYou won, WELL DONE!") 
            score = score + 1 
            print ("your score is,", score) 
            difficultyINSANE() 
 
        guess = input("\nGuess a letter:").lower() 
        guesses += guess    
        if guess not in word:   
            fails += 1         
            print ("\nWrong") 
 
            if fails == 1: 
                print ("You have", + fails, "fail....WATCH OUT!" ) 
            elif fails >= 2 and fails < 10: 
                print ("You have", + fails, "fails....WATCH OUT!" )  
            if fails == 10:            
                print ("You Loose\n") 
                print ("your score is, ", score) 
                print ("the word was,", word) 
                score = 0  
                difficultyINSANE() 

编辑:

我是这样读的

INSANEWORDS = open("create.txt","r+")  
words = []  
for item in INSANEWORDS: 
   words.append(item)  

请您参考如下方法:

您在每个单词的末尾都有一个 \n。 您应该在添加之前删除 \n 的单词:

INSANEWORDS = open("create.txt", "r+") 
words = [] 
for item in INSANEWORDS: 
    words.append(item.strip('\n')) 

之前:

之后: