我正在编写一个简单的纸牌游戏(类似Snap)。我已经让它正常运行了,但我感觉应该有更加优雅的解决方案。
给出一组赢得条件:
Y赢R
R赢B
B赢Y
等等
Y赢R
R赢B
B赢Y
等等
我想比较两个玩家的卡牌并将两张卡牌分配给赢家。 注意:我是在中学教学(没有OOP),希望能与学生讨论生成的代码。
我将最终条件留作elif,因为我想回头向选项列表添加更多卡牌。
if-elif链没有问题;我想知道是否有更加优美的解决方案。
#I have code that randomly selects from a list, but this is the basic
#idea:
p1=input("enter r,y or b")
p2=input("enter r,y or b")
stack1=[]
stack2=[]
if p1=="r" and p2=="b":
stack1.extend([p1,p2])
elif p1=="y" and p2=="r":
stack1.extend([p1,p2])
elif p1 =="b" and p2 =="y":
stack1.extend([p1,p2])
elif p2 =="r" and p1 =="b":
stack2.extend([p1,p2])
elif p2 =="y" and p1 =="r":
stack2.extend([p1,p2])
elif p2 =="b" and p1 =="y":
stack2.extend([p1,p2])
print(stack1)
print(stack2)
我从剩余代码中摘录了这段代码 - 所有卡片都是随机生成的,因此实际上不需要用户输入。
else: stack2.extend(....)
。 - Ocaso Protalif p1 + p2 in {'rb', 'yr', 'by'}: stack.extend([p1, p2])
等等呢? - Chris_Randsstack1.extend([p1, p2]) if (p1 + p2) in ['rb', 'yr', 'by'] else stack2.extend([p1,p2])
- MisterPhil