我对编码非常陌生,而且我正在努力学习我的第一个代码.
我想创建一个单词猜谜游戏,用户一次猜出几个字母的字符和位置.我坚持的步骤可以概括为:
>猜测和选择的单词输入;
>检查两个字母的猜测是否在所选单词的前2个字符中(每个正确字母10个点);和
>检查两个字母的猜测是否在所选单词的正确位置(每个正确字母50个点).
我似乎找不到办法做到这一点.这就是我到目前为止所拥有的.我希望自己继续使用其余的代码,但是,如果我无法超越第一步,那将是非常困难的!
def compute_score(guess,position,word):
""" Doc string """
score = 0
right_position_value = 100
wrong_position_value = 20
guess = input()
position = pos for char in guess
word_position = pos for char in word
for char in word:
if char in guess:
score += 10
if position == word_position:
score += 50
else:
score += 0
return score
guess_1 = input('guess the first 2 letters corresponding to letters 1 and2 of the unkown word!: ')
print('Your guess and score were: ', guess, score)
最佳答案 你比完成第1步所想的更接近.你已经有了输入猜测的代码,现在你只需输入选择的单词就可以了.您可能希望更改输入消息:
word = input('Choose your unknown word: ')
guess = input('guess the first 2 letters corresponding to letters 1 and2 of the unkown word!: ')
这就是第1步!
步骤2和3将需要更多的工作,因为你的compute_score函数存在一些问题.第一个问题是您立即覆盖传入的某些参数的值:
def compute_score(guess,position,word):
""" Doc string """
score = 0
right_position_value = 100
wrong_position_value = 20
guess = input()
overwrite their initial guess with this one.
position = pos for char in guess
word_position = pos for char in word
如果在使用它们之前重新分配这些变量,那么首先要将它们作为参数添加到函数中是没有意义的.但即使你修复了这个,你仍然会得到一个错误:
word_position = pos for char in word
我看到你正在尝试做什么,但是如果你要在下面的for循环中迭代单词的每个字母,你也可以只计算循环中每个字母的位置.这是一个巧妙的小技巧,你可以在for循环中使用它来做到这一点:
for idx, char in enumerate(word):
这不仅为您提供了单词(char)的每个字母,而且还为您提供了循环所进行的迭代计数(idx).例如:
>>> word = 'shape'
>>> for idx, char in enumerate(word):
... print(idx)
...
0
1
2
3
4
你可以使用这个迭代计数值作为字母的位置,希望这可以帮助你找出第3步(不可否认,我仍然不太确定位置参数的目的或位置猜测规则是如何工作的)
对于第2步,你也非常接近.目前,您正在检查两个字母的猜测是否在所选单词的任何位置.要仅检查前两个字母,您可以使用该单词的子字符串.在Python中,这是通过在检查期间“切片”除了单词的前2个字母来完成的:
for char in word:
if char in guess[:2]:
score += 10
在那里繁荣吧.
但是,我只是想让你知道你的代码中还有其他一些问题,主要的问题是最后一行中的猜测和得分变量没有在任何地方定义,而且你实际上从未调用过compute_score函数.在你的最后一行,你应该这样称呼它:
word = input('Choose your unknown word: ')
guess = input('guess the first 2 letters corresponding to letters 1 and2 of the unkown word!: ')
print('Your guess and score were: ', guess, calculate_score(guess, 0, word))
在示例中,我只是将0作为位置传递,因为游戏的位置规则仍然在我身上丢失.不过,如果您提供更详细的解释,我可以编辑此内容.