【发布时间】:2020-11-14 10:28:47
【问题描述】:
作为大多数学习 python 的人,我的任务是制作一个石头剪刀布游戏。截至目前,我有一个代码,如果你只运行一次,它就可以工作。我的问题是它需要循环运行,一直运行到用户或计算机获胜三次。这就是我没有放置循环的情况:
ug = input("Please enter your choice for: rock, paper, or scissors: ")
comp = [ ]
user = [ ]
random = np.random.randint(0, 3, 1)
# 1). Converts the randomly generated computer guess to str
def guessC(random):
if random == 0:
return ("R")
if random == 1:
return ("S")
if random == 2:
return ("P")
compg = guessC(random)
# prints the user guess (ug) and comp guess (compg)
print("You guessed: ", ug)
print("The computer guessed: ", compg)
#2). Determine winner
def rockpaperscisccor(compg, ug):
if compg == "R":
if ug == "R":
return 0,0
elif ug == "S":
return 1,0
elif ug == "P":
return 0,1
if compg == "P":
if ug == "P":
return 0,0
elif ug == "R":
return 1,0
elif ug == "S":
return 0,1
if compg == "S":
if ug == "S":
return 0,0
elif ug == "P":
return 1,0
elif ug == "R":
return 0,1
cs,us = rockpaperscisccor(compg, ug)
# 3). take scores of game and append comp score to its own list and user score to
# own list
def tallyuserH(us):
user = [ ]
user.append(us)
tus = 0
for i in user:
tus += i
return tus
sus = tallyuserH(us)
def compuserH(cs):
comp = [ ]
comp.append(cs)
tcs = 0
for i in comp:
tcs += i
return tcs
scs = compuserH(cs)
# 4). Score counter to determine score
def scorecounter(scs, sus):
if scs == 3:
print("The computer wins!", cs, "-", us, "!")
elif sus == 3:
print("You win!", us, "-", cs, "!")
elif scs > sus:
print("The computer leads!", cs, "-", us, "!")
elif sus > scs:
print("You lead!", us, "-", cs, "!")
elif sus == scs:
print("The score is tied at", cs, "-", us, "!")
else:
print("That doesn't seem to be a valid input")
scorecounter(scs,sus)
这是我将它放入 while 循环时所得到的。它在我希望它在一个玩家到达 3 时停止的地方无限运行:
print("Lets play rock, paper, scissor!")
def thegame():
i = 0
ug = input("Please enter your choice for: rock, paper, or scissors: ")
random = np.random.randint(0, 3, 1)
compg = guess(random)
print("You guessed: ", ug)
print("The computer guessed: ", compg)
cs,us = rockpaperscisccor(compg, ug)
sus = tallyuser(us)
scs = compuser(cs)
print ("user score is", sus)
print ("comp score is", scs)
while i < 6:
if scs == 3:
print("The computer wins!", cs, "-", us, "!")
elif sus == 3:
print("You win!", us, "-", cs, "!")
elif scs > sus:
print("The computer leads!", cs, "-", us, "!")
elif sus > scs:
print("You lead!", us, "-", cs, "!")
elif sus == scs:
print("The score is tied at", cs, "-", us, "!")
else:
print("That doesnt seem to be a valid input")
i += 1
return i
def guess(random):
if random == 0:
return ("R")
if random == 1:
return ("S")
if random == 2:
return ("P")
def tallyuser(us):
user = [ ]
user.append(us)
tus = 0
for i in user:
tus += i
return tus
def compuser(cs):
comp = [ ]
comp.append(cs)
tcs = 0
for i in comp:
tcs += i
return tcs
thegame()
我不知道如何构造 While 循环。此外,“计分功能”需要保留自己的部分,这意味着我不能将那部分嵌套在我确定获胜者的地方。如果这有意义!
谢谢,
雷切尔
【问题讨论】:
-
我正在初始化的变量在哪里?它在循环中也不会改变,这就是为什么它是无限的。
-
@luthervespers 我应该是圆的!抱歉,我不知道如何让它每次都计数。
标签: python while-loop