Skip to content

Instantly share code, notes, and snippets.

@gogvale
Last active December 1, 2019 03:01
Show Gist options
  • Save gogvale/3ed02a5a58b1323de7c74733cbe0f698 to your computer and use it in GitHub Desktop.
Save gogvale/3ed02a5a58b1323de7c74733cbe0f698 to your computer and use it in GitHub Desktop.
War Card Game in Python using OOP https://en.wikipedia.org/wiki/War_(card_game)
#!/usr/bin/python3
from random import shuffle, randint
import time
SUITE = "H D S C".split()
RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split()
class Card:
def __init__(self, suite: str, rank: str):
self.suite = suite
self.rank = rank
def __str__(self):
return str(self.suite+self.rank)
def value(self):
return RANKS.index(self.rank)
class Deck:
def __init__(self):
self.cards = list()
self.createDeck()
self.shuffleCards()
def createDeck(self):
for i in SUITE:
for j in RANKS:
self.cards.append(Card(i, j))
def shuffleCards(self):
shuffle(self.cards)
def splitInHalf(self):
return self.cards[:26], self.cards[26:]
class Player:
def __init__(self, name: str, hand: list):
self.name = name
self.stack = hand
def __str__(self):
return self.name
def cardsLeft(self):
return len(self.stack)
def insertIntoBottom(self, card):
if(isinstance(card, Card)):
self.stack = [card] + self.stack[:]
elif(isinstance(card, list)):
self.stack = card + self.stack
def drawCard(self):
print(f"{self} has drawn a card.")
if(self.cardsLeft() != 0):
return self.stack.pop()
class Game:
def __init__(self):
self.deck = Deck()
firstHalf, secondHalf = self.deck.splitInHalf()
self.PC = Player("PC", firstHalf)
self.User = Player("User", secondHalf)
self.isWar = False
self.gameOver = False
self.gameStart()
def gameStart(self):
while(not self.gameOver):
try:
pc = self.PC.drawCard()
user = self.User.drawCard()
print(f"User card: {user} ------- PC card: {pc}")
self.checkWinner(pc, user)
if(self.isWar):
self.war([pc, user])
self.printResults()
except Exception:
if(self.PC.cardsLeft() == 0):
print(f"{self.PC} has no cards left!")
print(f"{self.User} wins!")
elif(self.User.cardsLeft() == 0):
print(f"{self.User} has no cards left!")
print(f"{self.PC} wins!")
else:
print("Error")
self.gameOver = True
def printResults(self):
print(
f"USER: {self.User.cardsLeft()} ------- PC: {self.PC.cardsLeft()}")
# time.sleep(1)
def checkWinner(self, pc, user):
if(pc.value() > user.value()): # pc gets cards
print("PC wins round")
self.PC.insertIntoBottom([pc, user])
elif(user.value() > pc.value()): # user wins
print("User wins round")
self.User.insertIntoBottom([pc, user])
else: # tie
print("TIE! That means war!")
self.isWar = True
def war(self, cards: list):
pcDownCards = list()
userDownCards = list()
usedCards = cards[:]
totalCards = 0
for i in range(2):
pcDownCards.append(self.PC.drawCard())
userDownCards.append(self.User.drawCard())
totalCards += 2
winner = None
while(winner == None):
pcDownCards.append(self.PC.drawCard())
userDownCards.append(self.User.drawCard())
totalCards += 2
# Selecting random PC card
pcSelectedCard = pcDownCards[randint(0, 2)]
pcDownCards.remove(pcSelectedCard)
# Selecting random user card
userSelectedCard = userDownCards[randint(0, 2)]
userDownCards.remove(userSelectedCard)
# Printing results
print(f"User: {userSelectedCard} ---- PC: {pcSelectedCard}")
# Checking for winners
if(userSelectedCard.value() > pcSelectedCard.value()):
print(f"User wins {totalCards} cards")
winner = "user"
elif(userSelectedCard.value() < pcSelectedCard.value()):
print(f"PC wins {totalCards} cards")
winner = "pc"
else:
print("TIE!")
usedCards.append(pcSelectedCard)
usedCards.append(userSelectedCard)
for i in pcDownCards:
usedCards.append(i)
for i in userDownCards:
usedCards.append(i)
shuffle(usedCards)
if(winner == "user"):
self.User.insertIntoBottom(usedCards)
elif(winner == "pc"):
self.PC.insertIntoBottom(usedCards)
self.isWar = False
if __name__ == '__main__':
game = Game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment