我试图模拟(微小的)战争游戏!作为OOP的练习。我有一个循环,彼此玩两个甲板,但它似乎永远循环,一次又一次地重复相同的序列。输出到达一个牌组中有4个牌对象的点,然后循环重复。只有当两个Drawpile对象都大于零时,才应该运行循环。
ranks = [2,3,4,5,6,7,8,9,10,11,12,13,14] #for use of value comparison via index
suits =['Diamonds','Hearts','Clubs','Spades']
rounds = 0
class Card:
def __init__(self, rank, suit):
self.rank = rank
assert rank in ranks
assert suit in suits
self.suit = suit
def __repr_(self):
return '{} of {}'.format(self.rank,self.suit)
def __str__(self):
return '{} of {}'.format(self.rank,self.suit)
def __eq__(self, other):
if self.rank == other.rank:
return True
else:
return False
def __gt__(self, other): #gt compared via ordering of ranks index
if self.rank > other.rank:
return True
else:
return False
def __lt__(self, other):
if self.rank < other.rank:
return True
else:
return False
class Drawpile:
def __init__(self, pile =[]):
self.pile = pile
def __len__(self):
return len(self.pile)
def __getitem__(self, n):
return self.pile[n]
def add(self, n):
self.pile.append(n)
def draw(self):
if len(self) <= 0:
return None
return self.pile.pop(0)
dp1 = Drawpile([Card(2,'Diamonds'),Card(13,'Hearts'),Card(7,'Clubs')])
dp2 = Drawpile([Card(4,'Hearts'),Card(3,'Hearts'),Card(8,'Spades')])
while len(dp1) > 0 and len(dp2) > 0:
rounds += 1
c1 = dp1.draw()
c2 = dp2.draw()
print('Round ',rounds)
print('c1',c1, len(dp1))
print('c2',c2, len(dp2))
if c1 > c2:
dp1.add(c1)
dp1.add(c2)
else:
dp2.add(c1)
dp2.add(c2)
if len(dp1) > len(dp2):
print('Pile 1 Won!')
else:
print('Pile 2 Won!')
有人能告诉我这个循环到底在哪里被卡住了吗?我已经尝试过将其绘制出来,这是我的第二次重写。有什么想法吗?
答案 0 :(得分:0)
这是一个真正的无限循环:这就是游戏的本质。没有保证结束。这是你提供的一段跟踪(好工作!),它显示了循环。列出的第一轮和最后一轮是相同的;在这两种情况下,这些背后的甲板也是相同的。如果你想要一个有限的游戏,你需要对这种情况实施某种解决方案。
Round 64274
c1 13 of Hearts 3
c2 4 of Hearts 1
Round 64275
c1 2 of Diamonds 4
c2 8 of Spades 0
Round 64276
c1 7 of Clubs 3
c2 2 of Diamonds 1
Round 64277
c1 3 of Hearts 4
c2 8 of Spades 0
Round 64278
c1 13 of Hearts 3
c2 3 of Hearts 1
Round 64279
c1 4 of Hearts 4
c2 8 of Spades 0
Round 64280
c1 7 of Clubs 3
c2 4 of Hearts 1
Round 64281
c1 2 of Diamonds 4
c2 8 of Spades 0
Round 64282
c1 13 of Hearts 3
c2 2 of Diamonds 1
Round 64283
c1 3 of Hearts 4
c2 8 of Spades 0
Round 64284
c1 7 of Clubs 3
c2 3 of Hearts 1
Round 64285
c1 4 of Hearts 4
c2 8 of Spades 0
Round 64286
c1 13 of Hearts 3
c2 4 of Hearts 1