在下面的程序中,if语句接近结尾的结果偶尔会出错,但我看不到其中的模式。我已经尽可能地调试了它,但我找不到我的错误。我很抱歉大量的代码,但我不知道代码中的错误在哪里我所知道的是它在下面的代码中的某处。
非常感谢帮助!
我在python方面经验不足,所以请详细解释任何答案
for i in range(1,10):
import random
Cards = list(range(0,8))
print("shuffling...")
random.shuffle(Cards)
#print(Cards)
PlayerCards = []
ComputerCards = []
CardsLen = int(len(Cards)) / 2
for i in range(int(CardsLen)):
PlayerCards.append(Cards[0])
del Cards[0]
ComputerCards.append(Cards[0])
del Cards[0]
#print(PlayerCards)
#print(ComputerCards)
Ab5s = ['9', '12', '1', '10', '5', '6', '6', '8']
#print(Ab5s)
Ab5sS = sorted(Ab5s, key = int)
#print(Ab5sS)
AbNames = ['Magic', 'Cunning', 'Courage', 'Wisdom', 'Temper']
#print(AbNames)
Ab5Name = AbNames[4]
AbNamesDict = {5: Ab5s}
PlayerCardNum = PlayerCards[0]
ComputerCardNum = ComputerCards[0]
PlayerCardAb5 = Ab5s[PlayerCardNum]
ComputerCardAb5 = Ab5s[ComputerCardNum]
PlayerAbVal = Ab5s[PlayerCardNum]
ComputerAbVal = Ab5s[ComputerCardNum]
#print(PlayerAbVal)
#print(ComputerAbVal)
while True:
try:
PlayerAbUse = "Temper" #input("Which ability do you want to use ")
PlayerAbUse = PlayerAbUse.title()
PlayerAbNum = (AbNames.index(PlayerAbUse) + 1)
break
except ValueError:
print("error")
continue
AbList = AbNamesDict[PlayerAbNum]
PlayerAbVal = (AbList)[PlayerCardNum]
ComputerAbVal = (AbList)[ComputerCardNum]
#print(PlayerAbVal)
#print(ComputerAbVal)
print("Player has " + PlayerCardAb5 + " " + Ab5Name)
print("Computer has " + ComputerAbVal + " " + Ab5Name)
WonCards = []
#This is where I believe it is going wrong
if PlayerAbVal < ComputerAbVal:
Winner = 0
else:
if PlayerAbVal == ComputerAbVal:
Winner = 2
else:
Winner = 1
WonCards.append(PlayerCards.pop(0))
WonCards.append(ComputerCards.pop(0))
if Winner == 0:
print("Computer Win ")
while len(WonCards) > 0:
ComputerCards.append(WonCards.pop(0))
print("")
else:
if Winner == 1:
print("Player Win ")
while len(WonCards) > 0:
PlayerCards.append(WonCards.pop(0))
print("")
else:
print("Draw ")
Winner = random.randint(1,2)
答案 0 :(得分:1)
您的问题是您正在比较字符串,而不是数值。我最初的想法是你在Python 2中,但实际上这个失败也可以用lexicographical ordering
来解释将列表Ab5s = [9, 12, 1, 10, 5, 6, 6, 8]
更改为包含整数。所以:
print
要修复你的print("Player has " + str(PlayerCardAb5) + " " + Ab5Name)
,请转换为字符串,例如:
format()
或者,更好的是,使用print("Player has {} {}".format(PlayerCardAb5, Ab5Name))
:
int
正如您在其他评论中提到的,您的问题是您正在将字符串作为文件中的值读取。这并不能阻止您将值转换为Ab5s = ['9', '12', '1', '10', '5', '6', '6', '8']
Ab5s = [int(item) for item in Ab5s]
;最简单的方法可能就是列表理解:
map
还有其他方式,例如Ab5s = map(float, Ab5s)
,但我认为这是falling out of favour。
strtotime()
答案 1 :(得分:0)
只需修改您的if
语句即可强制该类型为int
。 (使用if..elif..else
获得更多的pythonicness)
if int(PlayerAbVal) < int(ComputerAbVal):
Winner = 0
elif int(PlayerAbVal) == int(ComputerAbVal):
Winner = 2
else:
Winner = 1