刽子手换字逻辑

2024-06-16 15:54:39 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
import sys
words=["tumble","sigh","correction","scramble","building","couple","ton"]
computer=random.choice(words)
attm=7
chosen_word=len(computer)*"*"

print(chosen_word)
while attm>0:
    print(computer)
    print(chosen_word)
    player_guess=str(input("guess: "))
    if len(player_guess)>1:
        player_guess=str(input("enter one character only: "))
    if player_guess in computer:
        print("you're right")
        attm==attm
        for i in chosen_word:    
            player_guess=chosen_word.replace(chosen_word,player_guess)
            print(chosen_word)
    else:
        print("wrong!")
        attm-=1
        
    print("attempts= ",attm)
       
    
        
         
if attm==0:
    print("you lost")
    sys.exit

我希望每当玩家猜到它被替换为选中的单词时,正确的角色就会替换明星 如果单词是“ton”,它将显示如下***如果玩家猜的是(t),所选单词将变成(t**),依此类推 简单语法更可取,因为我是python新手


Tags: importlenifsysrandom单词computerword
1条回答
网友
1楼 · 发布于 2024-06-16 15:54:39

在python中不能更改字符串,它们是不可变的。改为使用列表

list(string)chosen_word更改为list,并在相应的索引处替换/更改它们。要打印,只需使用"".join(list)创建一个新的字符串,以便很好地打印它

此外,您还出现了一个错误,您将其与所选的WOR进行了比较,这些WOR都是*,而不是实际的字母,因此除非您输入*,否则您将永远找不到匹配项

下面是完整的示例:

import random
import sys
words = ["tumble","sigh","correction","scramble","building","couple","ton"]
computer = random.choice(words)
attm = 7
chosen_word = ["*" for i in range(len(computer))]

while "*" in chosen_word and attm > 0:    
    print(computer)
    print("".join(chosen_word))
    player_guess = str(input("guess: "))[0] # take only the first character
    if player_guess in computer:
        print("you're right")
        for idx, ch in enumerate(computer):
            if player_guess == ch:
                chosen_word[idx] = ch
        print("".join(chosen_word))
    else:
        print("wrong!")
        attm -= 1
        
    print("attempts: ",attm)
       
    
        
if attm > 0:
    print("You won!")      
else:
    print("You lost")
sys.exit

相关问题 更多 >