我正在为 python 创建一个策划者风格的游戏,到目前为止,我已经修改了一个我在网上找到并修复了大多数错误,但它不会在 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
您可以正确使用 randint()方法,但不能将 char 附加到字符串中。如果您按如下方式更改代码,则第一个 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
你的代码中有一堆问题:
您需要添加import random
(在第一个打印语句之前)
secretCode = ('BYRG')
tosecretCode = []
修复缩进
在第二个同时将fullMatches <= 4
更改为fullMatches < 4
你应该学习的第一件事是使用xrange
来实现一个 for 循环,而不是带有显式变量初始化和增量的 while 循环,例如第一个 while 可以写为:
for i in xrange(0, 4):
colour = random.randint(0, 5)
secretCode.append(colours[colour])
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(33条)