【发布时间】:2017-02-16 22:46:39
【问题描述】:
了解一些背景知识:MasterMind® 是 Mordechai Meirovitz 在 1970 年代初期发明的一款密码破解游戏。在这场比赛中, 一名玩家——代码大师——负责生成由四种颜色序列组成的代码。一种 第二个玩家——密码破解者——试图猜测密码。每次猜测后,码主提供 关于猜测的反馈。具体来说,代码大师会告诉代码破解者有多少种颜色是正确的 以及有多少颜色在正确的位置。密码破解者继续猜测密码,直到他们 能够成功破解密码。密码破解者的“分数”是它需要破解的猜测次数 代码。
该计划的目标是:
- 定义有效颜色。
- 使用有效颜色生成密码。
- 只要我还没有猜到代码:请用户猜;更新猜测的数量。确保猜测有效
- 确定正确颜色的数量
- 确定正确位置的数量
- 将此反馈提供给代码破解者
- 向用户报告最终得分
我只是自信地完成了第 1 步和第 2 步。我的问题是如何获得 isValidGuess 函数来确定只有 validColors 存在。正如现在所写的那样,该函数没有包含validColors 参数,我不完全确定为什么。对于每个函数,都有一个函数应该做什么的简要说明。
-注意- 我不希望有人为我编写整个代码,只是为了帮助我使用 isValidGuess 函数。
import random
validColors = ["R", "G", "B", "Y", "O", "P"]
def generateCode(validColors):
#input: takes a string that represents validColors
#action: builds a string of length 4; each character is picked at random
# from the validColors
#return: a string of length 4 representing the codemaster's secretCode
secretCode = random.sample(validColors, 4)
return secretCode
def isValidGuess(guess, validColors):
#input: guess and validColors as strings
#action: ensures that the guess is the right length and only contains
# valids colors
#return: boolean value to isValidGuess
isValidGuess = False
if len(guess) != 4:
print("Invalid, guess again.")
elif len(guess) == 4:
isValidGuess = True
return isValidGuess
#def correctLocationCount(secretCode, guess):
#input: secretCode and guess as strings
#action: character by character comparison of the two strings and
# updates a counter every time they match
#return: the counter
#def correctColorCount(secretCode, guess, validColors):
#input: secretCode, guess, and valid colors as strings
#action: looks at each valid color and counts how many times that color
# appears in the code and how many times it appears in the guess
# Compare these counts to determine how many colors were guessed
#return: the count
def masterMind():
generateCode(validColors)
guess = input("What is your guess: ")
result = isValidGuess(guess, validColors)
while result == False:
guess = input("What is your guess: ")
result = isValidGuess(guess, validColors)
【问题讨论】:
-
与您所问的颜色问题无关:您确定您的
isValidGuess函数应该循环并在看到给出的猜测无效时提示新猜测?我希望它在这种情况下应该只返回False(并让调用代码进行循环)。当前代码会出现问题,因为调用代码将无法访问您的新guess值。 -
这是真的,我什至没有想到这一点。我将循环编辑为 if 语句,但我仍然遇到
isValidGuess无法识别validColors参数的问题。
标签: python python-3.x