【发布时间】:2014-10-04 15:20:55
【问题描述】:
我一直在家里使用 Python 制作基于文本的游戏,但在创建玩家和敌人之间的一小部分战斗时遇到了麻烦。战斗应该包括两个随机掷骰;一个给玩家,一个给外星人。如果外星人掷得比玩家高,则应将 +1 添加到 alien_wins 计数器,如果玩家获胜,则应将 +1 添加到 player_wins 计数器。
我想要发生的是当 player_wins 计数器达到 3 时,循环将停止并产生一条消息,当 alien_wins 达到 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和alien_wins <= 3继续循环吗? -
第一次迭代时
return为什么会有循环?另外,为什么return(在alien_roll == player_roll分支中)之后有代码? -
是的,没错。我希望它循环,直到两者之一达到 3,然后产生一条消息。
-
抱歉,我不确定那段代码。
标签: python if-statement while-loop tkinter