【问题标题】:hangman replacing characters logic刽子手替换字符逻辑
【发布时间】:2020-07-20 11:39:45
【问题描述】:
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

我希望每当玩家猜到它在 selected_word 中被替换时,正确的字符替换星星 如果单词是“ton”,它会像这样显示 *** 如果玩家猜的是 (t) 选择的单词变成 (t**) 等等 简单的语法更可取,因为我是 python 新手

【问题讨论】:

  • 您有问题吗?
  • @ForceBru 抱歉,这很令人困惑,但我尽力描述了这个问题,每次猜测正确时如何用字符替换星号
  • 这部分问题自然属于它自己的函数——一个将所选单词和猜测的字母作为输入并返回要显示为输出的字符串。编写、测试和调试该功能——然后使用它。试图在不使用任何函数的情况下做一个刽子手游戏会导致代码不可读。至于如何做——只需在迭代所选单词时构建字符串。

标签: python arrays python-3.x list


【解决方案1】:

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

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

此外,您在与所选的 wors 进行比较时遇到了一个错误,即全部为 * 而不是实际的字母,因此除非您输入 *,否则您将永远找不到匹配项。

这里是完整的例子:

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

【讨论】:

  • chosen_list = ["*" for _ in computer]chosen_list = ["*" for _ in range(len(computer))] 将是创建列表的更直接的方法,而无需首先创建通过加入星号列表创建的单词。另外,attm==attm 定义为 true,但不用于任何用途,我还建议 OP 将其删除。
  • 您还想将while attm>0: 更改为while "*" in chosen_word and attm > 0:。否则,即使用户猜对了单词,while 循环也会继续。
  • 我不明白要使用哪些变量作为获胜条件,两个变量必须相等,一个是计算机,一个是另一个变量,您添加的 for 循环包含很多新语法,这就是为什么我我很困惑
  • 我并没有在您的代码中添加太多更改,我只是向您展示了如何正确替换单词中的星号。我也尝试结合以前 cmets 的一些建议,但我专注于您的问题,即如何替换星号
  • @FirasChebil 获胜条件在底部(我添加了它)。如果 while 循环退出,你和你还有尝试,你赢了。如果它因为您没有更多尝试而退出,那么您就输了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 2019-02-17
  • 2016-04-07
  • 1970-01-01
相关资源
最近更新 更多