我正在编写游戏,并且希望重做部分代码。代码中的注释显示了我要重做的内容。
import random
def getRandom():
#this is the code I want to rerun (guess code) but I don't want to reset "players" and "lives"
players = 10
lives = 5
myGuess = input("What number do you choose")
compGuess = random.randint(1,5)
compGuess = int(compGuess)
print(f"Computer chose {compGuess}")
if compGuess == myGuess:
players = players - compGuess
print(f"You took out {compGuess} players")
print(f"There are {players} players left")
#run guess code
else:
lives -= 1
print(f"You lost a life! You now have {lives} lives remaining")
#run guess
getRandom()
答案 0 :(得分:0)
是的,我认为您应该首先创建一个心理模型。
您想发生什么以及如何发生?
如果您想“重做”一些东西,听起来像是一个循环,请尝试使用退出的方法在自己的末端创建一个“可自我调用”的函数。
如果创建一个函数,则可以在其内部调用它。
示例:
def testfunction(value):
a = value
b = 2
c = a + b
testfunction(c)
但是添加一些摆脱这种循环的方法会很有趣。
答案 1 :(得分:0)
您需要添加一个循环。考虑一下您的循环条件是什么,循环内部或外部需要什么。我认为您正在寻找类似这样的东西。
import random
def getRandom():
players = 10
lives = 5
while(lives > 0):
myGuess = input("What number do you choose")
compGuess = random.randint(1,5)
compGuess = int(compGuess)
print(f"Computer chose {compGuess}")
if compGuess == myGuess:
players = players - compGuess
print(f"You took out {compGuess} players")
print(f"There are {players} players left")
else:
lives -= 1
print(f"You lost a life! You now have {lives} lives remaining")
getRandom()
答案 2 :(得分:0)
由于您不想重置玩家和生活变量,因此可以在函数外部将其声明为全局变量,然后每个函数将具有相同的变量副本,因此您将不会重置它。有关更多参考,请参见这里:https://www.w3schools.com/python/gloss_python_global_variables.asp,以了解有关全局变量的更多信息。正如Ngeorg提到的那样,您需要有一个循环和某种条件来重新运行代码并在适当的时间停止它。