【发布时间】:2020-03-04 03:10:46
【问题描述】:
我对编码比较陌生,想用字母而不是颜色/数字创建一个策划游戏。
我的 MasterMind 中的密码是 4 个字母的序列。密码中的每个字母都是唯一的,从“A”到“H”。有效密码的一些示例是“ABDF”、“EGHC”和“DAFE”。
以下示例无效:
- “ABBG” - 它包含“B”的重复字符。
- “LHAD” - 它包含字符“L”,超出“A”到“H”的范围。
- “DBA”——它只包含 3 个字符,而不是必需的 4 个。
我目前已经完成了:
import random
def chooseOneLetter (base1, base2):
ratio = 10
seed = int(random.uniform (0, ratio*len(base1)+len(base2)))
if seed < ratio*len(base1):
chosenLetter = base1[int(seed/ratio)]
base1.remove(chosenLetter)
else:
chosenLetter = base2[(seed - ratio*len(base1))]
base2.remove(chosenLetter)
return chosenLetter
def getSecretCode(base1, base2):
secretCode = ""
for i in range(4):
chosenLetter = chooseOneLetter (base1, base2)
secretCode += chosenLetter
return secretCode
# base1 = ["A", "B", "C", "D"]
# base2 = ["E", "F", "G", "H"]
但是,我想再包含 2 个变量。第一个变量引用正确位置的字母列表,如果猜测中的字母不正确,则引用 None。第二个变量引用了一个字典,其中字母在错误位置被猜测为键,字母在错误位置被猜测的次数作为值。
例如如果密码是BAFD,
第一个变量引用 ['B', None, None, None]。 玩家已经正确猜到字母B在第一位,但其他位置的其他字母都是错误的。
第二个变量引用 {'A': 2, 'B': 1, 'D': 2}。 到目前为止,玩家已经猜对了 3 个字母:A 猜错了两次,B 猜错了一次,D 猜错了两次。
我也在寻找游戏引擎来提示用户玩另一个游戏并在它不符合条件时重新输入字符串。它应该看起来像这样。
Enter a guess to continue or RETURN to quit: abda
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: ade
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: asbc
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: abcd
The guess is not correct, attempt no. 1
The correct letters in correct positions: [None, None, None,
None]
The correct letters and the number of times found in incorrect
positions: {'B': 1, 'C': 1, 'D': 1}
Enter a guess to continue or RETURN to quit: dhcb
The guess is not correct, attempt no. 2
The correct letters in correct positions: [None, None, None,
'B']
The correct letters and the number of times found in incorrect
positions: {'B': 1, 'C': 2, 'D': 2, 'H': 1}
Enter a guess to continue or RETURN to quit: cdhb
You guessed it correctly in 3 attempts, the secret word is CDHB
Do you want to play again? Y to play again: y
非常感谢您的帮助!
【问题讨论】:
标签: python validation procedural-programming