我正在为python创建一个mastermind样式游戏,到目前为止我修改了一个我在网上找到的并修复了大部分错误但它不会在python中运行,例如它不会接受random.randint()
表达式我在网上找到了。
主要是它只是想要检查,如果你指出你发现的任何错误并且可能发布一些建议我会很感激吗?
这是我的代码:
print("-----------------------------------MASTERMIND-----------------------------------")
colours = ['B', 'R', 'Y', 'G', 'O']
secretCode = ('BYRG')
i = 0
while i < 4:
colour = random.randint(0, 5)
secretCode.append(colours[colour])
i = i+1
print("Secret: "), secretCode
fullMatches = 0
guessNum = 1
while (fullMatches <= 4):
fullMatches = 0
partialMatches = 0
secretCodeCopy = secretCode[:]
guess = []
print("Guess:"), guessNum
i = 0
while i < len(secretCode):
print("Enter your 4 colour guess from:")
print(colours)
colour = raw_input()
guess.append(colour)
i = i+1
i = 0
while i < len(guess):
if guess[i] == secretCodeCopy[i]:
fullMatches = fullMatches + 1
secretCodeCopy[i] = 'X'
guess[i] = 'Y'
i = i+1
i = 0
while i < len(guess):
j = 0
while j < len(secretCodeCopy):
if guess[i] == secretCodeCopy[j]:
partialMatches = partialMatches + 1
secretCodeCopy[j] = 'X'
guess[i] = 'Y'
j = j+1
i = i+1
print(fullMatches,)
print(" blacks")
print(partialMatches,)
print(" whites")
if fullMatches == 4:
print("You guessed it in",)
print(guessNum)
guessNum = guessNum+1
答案 0 :(得分:1)
正确使用randint()方法,但不能将字符串附加到字符串。例如,如果您按如下方式更改代码,则第一个while循环将起作用:
import random
print("---------------------------------MASTERMIND-----------------------------------")
colours = ['B', 'R', 'Y', 'G', 'O']
secretCode = 'BYRG'
i = 0
while i < 4:
colour = random.randint(0, 5)
secretCode += colours[colour]
i = i+1
print("Secret: "), secretCode
答案 1 :(得分:1)
您的代码中存在许多问题:
您需要添加import random
(在第一个打印声明之前)
将secretCode = ('BYRG')
更改为secretCode = []
修复缩进
fullMatches <= 4
更改为fullMatches < 4
的第二个
显然,这并不是一个非常流利的python的人写的。或许,您应该学习的第一件事是使用xrange
来实现for循环,而不是使用显式变量初始化和增量的while循环,例如第一次可以写成:
for i in xrange(0, 4):
colour = random.randint(0, 5)
secretCode.append(colours[colour])
答案 2 :(得分:0)