Answer:
Here is a console-based C# program for the card game War:
Explanation:
using System;
using System.IO;
namespace WarCardGameConsole
{
class WarCardGame
{
// Array to hold 52 cards
int[] deck = new int[52];
// Player and computer scores
int playerScore;
int computerScore;
// File to record results
StreamWriter results;
// Fill deck with cards
void FillDeck()
{
// Add cards to deck
for (int i = 0; i < deck.Length; i++)
{
deck[i] = i;
}
}
// Select random card
int SelectCard()
{
// Generate random index
Random rand = new Random();
int index = rand.Next(deck.Length);
// Remove selected card from deck
int card = deck[index];
deck[index] = deck[deck.Length - 1];
Array.Resize(ref deck, deck.Length - 1);
// Return selected card
return card;
}
// Play one round of war
void PlayRound()
{
// Select cards for player and computer
int playerCard = SelectCard();
int computerCard = SelectCard();
// Display cards
Console.WriteLine($"Player card: {playerCard} Computer card: {computerCard}");
// Check who has higher card
if (playerCard > computerCard)
{
playerScore++;
Console.WriteLine("Player wins this round!");
}
else if (computerCard > playerCard)
{
computerScore++;
Console.WriteLine("Computer wins this round!");
}
else
{
Console.WriteLine("Tie! No points awarded.");
}
// Pause before next round
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
void PlayGame()
{
// Fill deck with cards
FillDeck();
// Play 26 rounds
for (int i = 0; i < 26; i++)
{
PlayRound();
}
// Display final scores
Console.WriteLine($"Player final score: {playerScore}");
Console.WriteLine($"Computer final score: {computerScore}");
// Determine winner
if (playerScore > computerScore)
{
Console.WriteLine("Player wins the game!");
}
else if (computerScore > playerScore)
{
Console.WriteLine("Computer wins the game!");
}
else
{
Console.WriteLine("Tie game!");
}
// Record results in file
results.WriteLine($"{DateTime.Now} - {playerScore} to {computerScore}");
// Play again?
Console.Write("Play again? (Y/N) ");
string input = Console.ReadLine();
if (input.ToUpper() == "Y")
{
// Restart game
playerScore = 0;
computerScore = 0;
PlayGame();
}
else
{
// Close file and exit
results.Close();
Environment.Exit(0);
}
}
static void Main(string[] args)
{
// Create game object
WarCardGame game = new WarCardGame();
// Check if results file exists
if (!File.Exists("JohnDoe Results.txt"))
{
// Create file
game.results = File.CreateText("JohnDoe Results.txt");
}
else
{
// Open existing file
game.results = File.AppendText("JohnDoe Results.txt");
}
// Play game
game.PlayGame();
}
}
}