我在家里用Python制作了一个基于文本的游戏,在玩家和敌人之间创建一个小部分的战斗时遇到了麻烦。战斗应该包括两个随机掷骰;一个是玩家的,一个是外星人的。如果外星人掷得比玩家高,那么+1应该被添加到外星人的赢球计数器中,如果玩家赢了+1应该被添加到玩家的赢球计数器中。在
我想发生的是,当玩家赢的计数器达到3时,循环将停止并产生一条消息,同样的情况也应该发生在外星人的赢球数达到3时,但我有困难使其工作。任何帮助都将不胜感激,谢谢!在
import random
from Tkinter import *
def Fight():
player_wins = 0
alien_wins = 0
while player_wins <= 3:
player_roll = random.randint(0, 10)
alien_roll = random.randint(0, 7)
if player_roll > alien_roll:
contents.set("You manage to fire a shot of your laser pistol and the alien backs off.")
player_wins += 1
return
elif alien_roll > player_roll:
contents.set("The alien reaches out and strikes you with its claws.")
alien_wins += 1
return
elif alien_roll == player_roll:
contents.set("You both grapple eachother and eventually back off.")
return
if player_wins == 3:
contents.set("You manage to overcome the alien. It leaps from wall to wall and crawls into the vents.")
win = True
break
elif alien_wins == 3:
contents.set("You lose the fight to the alien. Game Over!")
break
base = Tk()
contents = StringVar()
display = Message(base, textvariable = contents, relief=RAISED)
display.pack()
enterbutton = Button(base, text = 'Try Again', command = Fight).pack()
base.mainloop()
我清理了一些东西。通过使循环依赖于}同时是{},修复了循环的主要问题。这样,每当其中一个命中
player_wins
和{3
,循环终止,控制转到下面的if/else
语句,该语句将设置优胜者。在您也不需要那些
break
语句,因为这完全脱离了循环。您可能正在考虑continue
,它只会转到循环的下一个迭代,但是即使这样也不需要,因为循环的整个内容只是一个if/else
语句,因此只执行一个分支。在另外,在
elif
中检查两个rolls
是否相等是不必要的,因为您已经排除了两个都不大于/小于另一个,所以可以假设它们是相等的。最后一个if/else
也一样,你可以检查谁拥有3
。如果我们不在循环中,我们知道有人有3
,所以我们只需要检查一个玩家的分数。在当任一条件(points<;=3)为
True
时,您希望继续战斗(循环)。您需要向while
循环添加另一个条件。在你只想在战斗结束后从函数返回,所以删除所有这些返回,并在战斗结束后添加一个在循环之外的返回。只想在战斗结束后,你也只想创造信息。在
相关问题 更多 >
编程相关推荐