gpt4 book ai didi

python - 循环使用两个计数器

转载 作者:行者123 更新时间:2023-11-30 23:19:13 25 4
gpt4 key购买 nike

我一直在家里使用 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()

最佳答案

当任一条件(点<= 3)为时,您想继续战斗(循环)。您需要向 while 循环添加另一个条件。

您只想在战斗结束后从函数返回,因此删除所有这些返回并在战斗结束后添加循环之外的返回。另外,您只想在战斗结束后创建消息。

def Fight():

player_wins = 0
alien_wins = 0

while player_wins <= 3 and alien_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

elif alien_roll > player_roll:
contents.set("The alien reaches out and strikes you with its claws.")
alien_wins += 1

elif alien_roll == player_roll:
contents.set("You both grapple eachother and eventually back off.")

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
elif alien_wins == 3:
contents.set("You lose the fight to the alien. Game Over!")
return

关于python - 循环使用两个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26194195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com