我正在编写一个基于Accordion单人纸牌的python程序。我已经编写了上面的代码,并且在过去的几个小时里一直在玩它,但我似乎无法使循环正常运行。无论出于何种原因,它将只运行一次循环而不再请求输入,或者它将运行一次,询问输入,无论我输入什么,它都会崩溃。我在这里做错了什么想法?
这是我的代码:
import random
print("Command Options:")
print("1C - Play card C onto pile 1 position back, ignored if invalid")
print("3C - Play card C onto pile 3 positions back, ignored if invalid")
print("C - Count of undealt cards")
print("D - Deal next card")
print("H - Print this help screen")
print("R - Resign this game (quit early)")
print("X - Exit Program")
cards=['AC','2C','3C','4C','5C','6C','7C','8C','9C','TC','JC','QC','KC','AD','2D','3D','4D','5D','6D','7D','8D','9D','TD','JD','QD','KD','AH','2H','3H','4H','5H','6H','7H','8H','9H','TH','JH','QH','KH','AS','2S','3S','4S','5S','6S','7S','8S','9S','TS','JS','QS','KS']
random.shuffle(cards,random.random)
playable=[]
done=False
while not done:
move=input("Enter move: ")
move_upper=move.upper()
if move_upper == 'D':
playable.append(cards.pop())
print(playable)
if move_upper == 'X' or 'R':
done=True
if move_upper == 'H':
print("Command Options:")
print("1C - Play card C onto pile 1 position back, ignored if invalid")
print("3C - Play card C onto pile 3 positions back, ignored if invalid")
print("C - Count of undealt cards")
print("D - Deal next card")
print("H - Print this help screen")
print("R - Resign this game (quit early)")
print("X - Exit Program")
if move_upper == 'C':
k=0
for item in cards:
k+=1
print(K,'cards left')
答案 0 :(得分:3)
您误解了or
的工作原理。使用:
if move_upper in ('X', 'R'):
代替。
表达式move_upper == 'X' or 'R'
被解释为(move_upper == 'X') or 'R'
,而非空字符串总是被视为True
。因此,你本质上是在测试(move_upper == 'X') or True
,然后它真的是move_upper
并不重要。
你真的不需要在这里使用done
标志变量;使用break
来结束循环:
while True:
# ...
if move_upper in ('X', 'R'):
break
答案 1 :(得分:0)
我目前处于代码审查的状态,所以请原谅我。
cards = [ number + suite for number in 'A23456789TJQK' for suite in 'CDHS' ]
更具可读性,这样就减少了错误的可能性。