Certainly! Below is a complete Python script implementing the classic card game "War." This implementation is modular, using classes to represent the core components: Card, Deck, Player, and Game. The game supports 2 to 4 players, including AI-controlled players. It features a text-based interface with simple ASCII representations for the cards, handles user inputs and edge cases gracefully, and is extensively commented for clarity.
Brief Explanation:
- Card Class: Represents a single playing card with a suit and rank. It includes methods to display the card and compare ranks.
- Deck Class: Represents a standard deck of 52 cards. It handles deck creation, shuffling, and dealing cards to players.
- Player Class: Represents a game participant, either human or AI-controlled. It manages the player's hand and score.
- Game Class: Manages the overall game flow, including setup, turns, handling wars (ties), and determining the winner.
- Main Execution: Initializes the game, prompts for the number of players, and starts the gameplay loop.
Complete Python Script:
import random
import sys
import time
# Define global variables for suits and ranks
SUITS = ['♠', '♥', '♦', '♣']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
# Define rank values for comparison
RANK_VALUES = {rank: index for index, rank in enumerate(RANKS, start=2)}
class Card:
"""
Represents a single playing card with a suit and rank.
"""
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
"""
Return a string representation of the card with simple ASCII art.
"""
return f"{self.rank}{self.suit}"
def value(self):
"""
Return the numerical value of the card for comparison.
"""
return RANK_VALUES[self.rank]
class Deck:
"""
Represents a standard deck of 52 playing cards.
"""
def __init__(self):
self.cards = [Card(suit, rank) for suit in SUITS for rank in RANKS]
def shuffle(self):
"""
Shuffle the deck of cards.
"""
random.shuffle(self.cards)
def deal(self, num_players):
"""
Deal the cards evenly to the specified number of players.
"""
# Calculate the number of cards per player
cards_per_player = len(self.cards) // num_players
# Distribute the cards
return [self.cards[i*cards_per_player:(i+1)*cards_per_player] for i in range(num_players)]
class Player:
"""
Represents a player in the game.
"""
def __init__(self, name, is_ai=False):
self.name = name
self.hand = []
self.score = 0
self.is_ai = is_ai
def play_card(self):
"""
Play the top card from the player's hand.
"""
if self.hand:
return self.hand.pop(0)
else:
return None
def has_cards(self):
"""
Check if the player still has cards.
"""
return len(self.hand) > 0
def add_cards(self, cards):
"""
Add won cards to the bottom of the player's hand.
"""
self.hand.extend(cards)
class Game:
"""
Manages the overall game flow and rules.
"""
def __init__(self):
self.players = []
self.deck = Deck()
self.deck.shuffle()
def setup_players(self):
"""
Set up the players for the game.
"""
while True:
try:
num_players = int(input("Enter number of players (2-4): "))
if num_players < 2 or num_players > 4:
print("Please enter a number between 2 and 4.")
continue
break
except ValueError:
print("Invalid input. Please enter a number between 2 and 4.")
for i in range(1, num_players + 1):
while True:
player_type = input(f"Is Player {i} a human or AI? (h/a): ").lower()
if player_type not in ['h', 'a']:
print("Invalid input. Enter 'h' for human or 'a' for AI.")
continue
name = input(f"Enter name for Player {i}: ") if player_type == 'h' else f"AI_Player_{i}"
is_ai = True if player_type == 'a' else False
self.players.append(Player(name, is_ai))
break
# Deal the cards to players
dealt_hands = self.deck.deal(num_players)
for player, hand in zip(self.players, dealt_hands):
player.hand = hand
def play(self):
"""
Start and manage the game loop.
"""
print("\nStarting the game of War!\n")
round_num = 1
while True:
print(f"--- Round {round_num} ---")
# Check if any player has all the cards
active_players = [player for player in self.players if player.has_cards()]
if len(active_players) == 1:
winner = active_players[0]
print(f"\n{winner.name} wins the game with all the cards!")
break
elif len(active_players) == 0:
print("All players have run out of cards. It's a tie!")
break
# Each player plays a card
table = []
for player in active_players:
card = player.play_card()
if card:
table.append((player, card))
print(f"{player.name} plays: {card}")
else:
print(f"{player.name} has no more cards to play.")
# Determine the highest card value
if not table:
print("No cards were played this round.")
break
max_value = max(card.value() for _, card in table)
winners = [player for player, card in table if card.value() == max_value]
# Collect the cards to be added to the winner's hand
spoils = [card for _, card in table]
if len(winners) == 1:
winner = winners[0]
winner.add_cards(spoils)
winner.score += 1
print(f"{winner.name} wins the round and takes {len(spoils)} cards.\n")
else:
# Handle war (tie)
print("War! Players are tied with the highest card.")
war_spoils = spoils.copy()
while len(winners) > 1:
war_table = []
for player in winners:
# Each player puts three cards face down and one face up
face_down = []
for _ in range(3):
card = player.play_card()
if card:
face_down.append(card)
else:
break
face_up = player.play_card()
if face_up:
war_table.append((player, face_up))
war_spoils.extend(face_down)
war_spoils.append(face_up)
print(f"{player.name} puts 3 cards face down and plays: {face_up}")
else:
print(f"{player.name} does not have enough cards to continue the war.")
if not war_table:
print("No players have enough cards to continue the war.")
break
max_war_value = max(card.value() for _, card in war_table)
winners = [player for player, card in war_table if card.value() == max_war_value]
if len(winners) == 1:
winner = winners[0]
winner.add_cards(war_spoils)
winner.score += 1
print(f"{winner.name} wins the war and takes {len(war_spoils)} cards.\n")
else:
print("War continues!\n")
# Display current scores
print("Current Scores:")
for player in self.players:
print(f"{player.name}: {player.score}")
print("\n")
round_num += 1
time.sleep(1) # Pause for readability
# Final Scores
print("\nFinal Scores:")
for player in self.players:
print(f"{player.name}: {player.score}")
print("\nThank you for playing War!")
def main():
game = Game()
game.setup_players()
game.play()
if __name__ == "__main__":
main()
How to Run the Script:
- Ensure you have Python installed on your system (version 3.x).
- Save the above script to a file named
war_game.py.
- Open a terminal or command prompt and navigate to the directory containing
war_game.py.
- Run the script using the command:
python war_game.py
- Follow the on-screen prompts to set up and play the game.
Example Gameplay:
Enter number of players (2-4): 2
Is Player 1 a human or AI? (h/a): h
Enter name for Player 1: Alice
Is Player 2 a human or AI? (h/a): a
Enter name for Player 2: AI_Player_2
Starting the game of War!
--- Round 1 ---
Alice plays: 7♠
AI_Player_2 plays: J♦
AI_Player_2 wins the round and takes 2 cards.
Current Scores:
Alice: 0
AI_Player_2: 1
--- Round 2 ---
Alice plays: K♣
AI_Player_2 plays: 5♥
Alice wins the round and takes 2 cards.
Current Scores:
Alice: 1
AI_Player_2: 1
...
Final Scores:
Alice: 26
AI_Player_2: 26
Thank you for playing War!
Note: The actual gameplay will vary each time due to the shuffling of the deck. This example demonstrates the flow and possible outcomes, including handling wars and updating scores.