War card game: Difference between revisions

Content added Content deleted
mNo edit summary
No edit summary
Line 175: Line 175:
Player 1 wins the game.
Player 1 wins the game.
</pre>
</pre>

=={{header|Python}}==
{{trans|Julia}}
<lang python>""" https://bicyclecards.com/how-to-play/war/ """

from numpy.random import shuffle

SUITS = ['♣', '♦', '♥', '♠']
FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
DECK = [f + s for f in FACES for s in SUITS]
CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))


class WarCardGame:
""" card game War """
def __init__(self):
deck = DECK.copy()
shuffle(deck)
self.deck1, self.deck2 = deck[:26], deck[26:]
self.pending = []

def turn(self):
""" one turn, may recurse on tie """
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()

card1, card2 = self.deck1.pop(0), self.deck2.pop(0)
rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]
print("{:10}{:10}".format(card1, card2), end='')
if rank1 > rank2:
print('Player 1 takes the cards.')
self.deck1.extend([card1, card2])
self.deck1.extend(self.pending)
self.pending = []
elif rank1 < rank2:
print('Player 2 takes the cards.')
self.deck2.extend([card2, card1])
self.deck2.extend(self.pending)
self.pending = []
else: # rank1 == rank2
print('Tie!')
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()

card3, card4 = self.deck1.pop(0), self.deck2.pop(0)
self.pending = [card1, card2, card3, card4]
print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='')
self.turn()

return True

def gameover(self):
""" game over who won message """
if len(self.deck2) == 0:
if len(self.deck1) == 0:
print('\nGame ends as a tie.')
else:
print('\nPlayer 1 wins the game.')
else:
print('\nPlayer 2 wins the game.')

return False


if __name__ == '__main__':
WG = WarCardGame()
while WG.turn():
continue
</lang>{{out}}
<pre>
8♠ K♠ Player 2 takes the cards.
3♠ 8♥ Player 2 takes the cards.
K♣ 4♠ Player 1 takes the cards.
Q♦ J♣ Player 1 takes the cards.
5♦ 6♦ Player 2 takes the cards.
A♥ Q♣ Player 1 takes the cards.
10♣ 5♥ Player 1 takes the cards.
J♦ 7♣ Player 1 takes the cards.
K♥ Q♠ Player 1 takes the cards.
2♦ 2♣ Player 1 takes the cards.
10♠ 9♥ Player 1 takes the cards.
9♠ 3♦ Player 1 takes the cards.
A♠ A♦ Tie!
? ? Cards are face down.
3♥ 8♦ Player 2 takes the cards.
5♣ 2♠ Player 1 takes the cards.
J♠ 4♦ Player 1 takes the cards.
2♥ 7♦ Player 2 takes the cards.

... et cetera ...

A♣ 4♣ Player 1 takes the cards.
7♣ 3♣ Player 1 takes the cards.
9♠ A♦ Player 2 takes the cards.
6♦ Q♠ Player 2 takes the cards.
7♦ 3♦ Player 1 takes the cards.
5♥ 2♥ Player 1 takes the cards.
A♣ A♥ Player 2 takes the cards.
4♣ 10♣ Player 2 takes the cards.
7♣ 10♥ Player 2 takes the cards.
3♣ 5♦ Player 2 takes the cards.
7♦ K♦ Player 2 takes the cards.
3♦ 8♣ Player 2 takes the cards.
5♥ J♦ Player 2 takes the cards.
2♥ 6♥ Player 2 takes the cards.

Player 2 wins the game.
</pre>



=={{header|Wren}}==
=={{header|Wren}}==