Moderna konstruktioner
“Your weapons… you will not need them.” - Yoda (obviously hadn’t met the List
Welcome to the final chapter, ung Padawan! Du har lärt dig The Force of Data, The Jedi Arts, Building the Rebel Alliance, och The Tactical Decisions. Nu är det dags för the most practical skills: working med collections, manipulating data, och building real galactic applications. Detta är din Rebel Arsenal - the tools every resistance fighter needs för practical operations!
Think of this kapitel som your utility belt, filled med practical tools som kommer make your daily coding som efficient som a well-organized rebel base. Vi’ll cover everything from managing pilot rosters to handling encrypted communications och planning mission schedules.
Listor - Dynamic Fleet Management (Better än fixed Imperial squadrons)
Arrays (som string[] pilots = {"Luke", "Wedge", "Biggs"}) har fixed size som Imperial doctrine - rigid och inflexible. Men Lists are dynamic som the Rebel Alliance - they can grow, shrink, och adapt to changing galactic situations!
Creating och Using Lists (Building Your Rebel Fleet)
// Skapa en empty squadron roster
List<string> rebelPilots = new List<string>();
// Add pilots as they join the cause
rebelPilots.Add("Luke Skywalker");
rebelPilots.Add("Wedge Antilles");
rebelPilots.Add("Biggs Darklighter");
rebelPilots.Add("Jek Porkins");
Console.WriteLine("=== RED SQUADRON ROSTER ===");
foreach (string pilot in rebelPilots)
{
Console.WriteLine($"Pilot: {pilot}");
}
// Eller create med initial rebels (like original Alliance founders)
List<string> foundingMembers = new List<string> { "Mon Mothma", "Bail Organa", "Leia Organa", "Garm Bel Iblis" };
// Display all founding members
Console.WriteLine("\n=== REBEL ALLIANCE FOUNDERS ===");
foreach (string founder in foundingMembers)
{
Console.WriteLine($"Founding Member: {founder}");
}
Practical List Operations (Fleet Management Commands)
List<string> starfighterModels = new List<string> { "X-wing", "Y-wing", "A-wing", "B-wing" };
Console.WriteLine("=== REBEL FLEET ANALYSIS ===");
// Count available ships (crucial för battle planning)
Console.WriteLine($"Available starfighter models: {starfighterModels.Count}");
// Check if specific ship type available
if (starfighterModels.Contains("X-wing"))
{
Console.WriteLine("X-wings available! Perfect för trench runs!");
}
// Find position i fleet roster
int xwingPosition = starfighterModels.IndexOf("X-wing");
Console.WriteLine($"X-wing is model #{xwingPosition + 1} in our fleet");
// Add new ship type to fleet (Rebellion grows!)
starfighterModels.Add("U-wing");
Console.WriteLine("U-wing transport added to fleet!");
// Remove outdated ship (som when Y-wings become too old)
starfighterModels.Remove("Y-wing");
Console.WriteLine("Y-wing retired from active service");
// Remove by position (like decommissioning specific ships)
starfighterModels.RemoveAt(0);
Console.WriteLine("First ship model decommissioned");
// Insert priority ship at beginning
starfighterModels.Insert(0, "T-70 X-wing");
Console.WriteLine("New T-70 X-wing added as priority fighter!");
Console.WriteLine("\n=== UPDATED FLEET ROSTER ===");
for (int i = 0; i < starfighterModels.Count; i++)
{
Console.WriteLine($"{i + 1}. {starfighterModels[i]}");
}
// Clear all ships (emergency evacuation protocol)
// starfighterModels.Clear(); // Uncomment only in dire situations!
String Manipulation - Decrypting Imperial Communications
Strings are like intercepted Imperial transmissions - you need to decode, analyze, och extract useful intelligence:
string interceptedMessage = " Secret Imperial Plan: Death Star II Construction ";
Console.WriteLine("=== REBEL INTELLIGENCE ANALYSIS ===");
// Basic intelligence gathering
Console.WriteLine($"Message length: {interceptedMessage.Length} characters");
Console.WriteLine($"UPPERCASE VERSION: {interceptedMessage.ToUpper()}");
Console.WriteLine($"lowercase version: {interceptedMessage.ToLower()}");
Console.WriteLine($"Clean message: '{interceptedMessage.Trim()}'"); // Remove space padding
// Content analysis (critical för rebel operations)
if (interceptedMessage.Contains("Death Star"))
{
Console.WriteLine("CRITICAL INTELLIGENCE: Death Star reference detected!");
Console.WriteLine("Alert all rebel cells immediately!");
}
if (interceptedMessage.StartsWith("Secret"))
{
Console.WriteLine("CLASSIFICATION: Secret Imperial document");
}
if (interceptedMessage.EndsWith("Construction"))
{
Console.WriteLine("CONSTRUCTION PROJECT: Active Imperial building detected");
}
// Decode structured data (like pilot assignments)
string pilotAssignments = "Luke-X-wing,Wedge-A-wing,Biggs-X-wing,Porkins-X-wing";
string[] assignments = pilotAssignments.Split(',');
Console.WriteLine("\n=== DECODED PILOT ASSIGNMENTS ===");
foreach (string assignment in assignments)
{
string[] details = assignment.Split('-');
string pilotName = details[0];
string shipType = details[1];
Console.WriteLine($"Pilot {pilotName} assigned to {shipType}");
}
// Replace classified info för secure communications
string secureMessage = interceptedMessage.Replace("Death Star", "Space Station");
string publicMessage = secureMessage.Replace("Secret", "General");
Console.WriteLine($"\nPublic version: {publicMessage}");
// Advanced string manipulation (code breaking)
string encryptedCoordinates = "Yavin-4 Base Location";
string[] locationParts = encryptedCoordinates.Split(' ');
Console.WriteLine($"\nTarget System: {locationParts[0]}");
Console.WriteLine($"Intel Type: {locationParts[1]} {locationParts[2]}");
Date och Time Operations - Mission Planning
Every rebel operation requires precise timing. DateTime helps you coordinate attacks, plan evacuations, och schedule important galactic events:
Console.WriteLine("=== REBEL MISSION TIMING SYSTEM ===");
// Current galactic standard time
DateTime now = DateTime.Now;
Console.WriteLine($"Current time: {now}");
// Mission planning dates
DateTime today = DateTime.Today;
Console.WriteLine($"Today's date: {today:yyyy-MM-dd}");
// Historical events (important för Rebellion timeline)
DateTime battleOfYavin = new DateTime(1977, 5, 25); // A New Hope release date as battle date
DateTime empireStrikesBack = new DateTime(1980, 5, 21); // Empire release as Imperial counterattack
DateTime returnOfJedi = new DateTime(1983, 5, 25); // Return as final victory
Console.WriteLine($"Battle of Yavin: {battleOfYavin:d MMMM yyyy}");
Console.WriteLine($"Imperial Counterattack: {empireStrikesBack:d MMMM yyyy}");
Console.WriteLine($"Final Victory: {returnOfJedi:d MMMM yyyy}");
// Calculate rebellion duration
TimeSpan rebellionDuration = returnOfJedi - battleOfYavin;
int rebellionYears = (int)(rebellionDuration.Days / 365.25);
Console.WriteLine($"Total Rebellion Duration: approximately {rebellionYears} years");
// Mission scheduling (adding time för future operations)
DateTime nextMission = DateTime.Now.AddDays(7);
DateTime evacuationDeadline = DateTime.Now.AddHours(72);
DateTime reinforcementArrival = DateTime.Now.AddMonths(2);
Console.WriteLine($"\n=== UPCOMING OPERATIONS ===");
Console.WriteLine($"Next mission: {nextMission:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Evacuation deadline: {evacuationDeadline:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Reinforcements arrive: {reinforcementArrival:yyyy-MM-dd}");
// Mission countdown
DateTime deathStarAttack = DateTime.Now.AddMinutes(30);
TimeSpan timeUntilAttack = deathStarAttack - DateTime.Now;
Console.WriteLine($"\n=== DEATH STAR ATTACK COUNTDOWN ===");
Console.WriteLine($"Attack begins in: {timeUntilAttack.Minutes} minutes and {timeUntilAttack.Seconds} seconds");
Console.WriteLine("All pilots to your ships!");
TryParse - Safe Input Handling (Better än Imperial data validation)
When rebels send coordinates eller battle reports, the data might be corrupted by Imperial interference. TryParse helps you handle this safely:
Console.WriteLine("=== REBEL COMMUNICATION SYSTEM ===");
Console.WriteLine("Enter number of available X-wings:");
string userInput = Console.ReadLine();
if (int.TryParse(userInput, out int xwingCount))
{
Console.WriteLine($"\nX-wing fleet status confirmed: {xwingCount} ships available");
if (xwingCount >= 20)
{
Console.WriteLine("EXCELLENT: Full squadron deployment possible!");
Console.WriteLine("Ready för Death Star assault!");
}
else if (xwingCount >= 10)
{
Console.WriteLine("ADEQUATE: Limited squadron operations available");
Console.WriteLine("Proceed med tactical missions only");
}
else if (xwingCount > 0)
{
Console.WriteLine("MINIMAL: Few fighters available");
Console.WriteLine("Focus on defensive operations");
}
else
{
Console.WriteLine("CRITICAL: No X-wings available!");
Console.WriteLine("Emergency evacuation protocols may be needed");
}
}
else
{
Console.WriteLine("COMMUNICATION ERROR: Invalid ship count received!");
Console.WriteLine("Imperial interference suspected - please retry transmission");
Console.WriteLine("Make sure you're transmitting numbers only (e.g., '12', not 'twelve')");
}
// Safe parsing för other critical data
Console.WriteLine("\nEnter pilot skill rating (0-100):");
string skillInput = Console.ReadLine();
if (double.TryParse(skillInput, out double skillRating))
{
if (skillRating >= 90)
Console.WriteLine("ELITE PILOT: Cleared för Death Star trench runs!");
else if (skillRating >= 75)
Console.WriteLine("EXPERIENCED PILOT: Regular missions approved");
else if (skillRating >= 50)
Console.WriteLine("STANDARD PILOT: Training missions recommended");
else
Console.WriteLine("NOVICE PILOT: Extended training required");
}
else
{
Console.WriteLine("Invalid skill rating format - please enter numeric value");
}
Random Number Generation - Tactical Variety (Like unpredictable rebel strategies)
Random numbers help simulate unpredictable events - perfect för adding variety to rebel operations och testing different scenarios:
Random galacticRandom = new Random();
Console.WriteLine("=== REBEL TACTICAL RANDOMIZATION SYSTEM ===");
// Random mission assignment (like rolling dice för dangerous missions)
int missionDifficulty = galacticRandom.Next(1, 11); // 1-10 scale
Console.WriteLine($"Mission difficulty roll: {missionDifficulty}/10");
if (missionDifficulty >= 8)
Console.WriteLine("EXTREME MISSION: Death Star assault level!");
else if (missionDifficulty >= 6)
Console.WriteLine("HIGH RISK MISSION: Imperial stronghold raid");
else if (missionDifficulty >= 4)
Console.WriteLine("MODERATE MISSION: Supply convoy escort");
else
Console.WriteLine("ROUTINE MISSION: Patrol duty");
// Random success probability (för mission planning)
int successChance = galacticRandom.Next(0, 101); // 0-100%
Console.WriteLine($"\nMission success probability: {successChance}%");
if (successChance >= 80)
Console.WriteLine("HIGH SUCCESS RATE: Proceed med confidence!");
else if (successChance >= 60)
Console.WriteLine("MODERATE SUCCESS RATE: Acceptable risk level");
else if (successChance >= 40)
Console.WriteLine("LOW SUCCESS RATE: Consider alternative strategies");
else
Console.WriteLine("MINIMAL SUCCESS RATE: Mission too dangerous - abort!");
// Random pilot selection (när you need to choose volunteers)
List<string> availablePilots = new List<string>
{
"Luke Skywalker",
"Wedge Antilles",
"Biggs Darklighter",
"Jek Porkins",
"Garven Dreis",
"Dutch Vander"
};
Console.WriteLine($"\n=== RANDOM PILOT SELECTION ===");
Console.WriteLine("Available pilots för dangerous mission:");
for (int i = 0; i < availablePilots.Count; i++)
{
Console.WriteLine($"{i + 1}. {availablePilots[i]}");
}
int randomPilotIndex = galacticRandom.Next(availablePilots.Count);
string selectedPilot = availablePilots[randomPilotIndex];
Console.WriteLine($"\nRANDOM SELECTION: {selectedPilot} volunteers för the mission!");
if (selectedPilot == "Luke Skywalker")
Console.WriteLine("The Force has guided this selection - may it be with you!");
// Random event simulation (för testing different scenarios)
Console.WriteLine($"\n=== BATTLE SIMULATION ===");
for (int round = 1; round <= 5; round++)
{
int rebelDamage = galacticRandom.Next(10, 31); // 10-30 damage
int imperialDamage = galacticRandom.Next(5, 26); // 5-25 damage
Console.WriteLine($"Round {round}: Rebels deal {rebelDamage} damage, Imperials deal {imperialDamage} damage");
if (rebelDamage > imperialDamage + 10)
Console.WriteLine(" - REBEL ADVANTAGE: Excellent tactics!");
else if (imperialDamage > rebelDamage + 10)
Console.WriteLine(" - IMPERIAL ADVANTAGE: Retreat recommended!");
else
Console.WriteLine(" - EVEN BATTLE: Fight continues!");
}
File Operations - Secure Rebel Data Storage
The Rebellion needs to store och access critical information securely. File operations help you save mission reports, pilot data, och tactical plans:
Console.WriteLine("=== REBEL DATA STORAGE SYSTEM ===");
// Creating mission report (vital för future operations)
string missionReport = @"=== DEATH STAR ASSAULT MISSION REPORT ===
Mission Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"
Mission Commander: General Dodonna
Primary Pilot: Luke Skywalker (Red Five)
Mission Objective: Destroy Death Star exhaust port
Mission Status: SUCCESS
Imperial Casualties: Death Star destroyed
Rebel Casualties: Minimal pilot losses
Special Notes: Force abilities confirmed in pilot Luke Skywalker
Next Steps: Prepare för Imperial retaliation
May the Force be with the Rebellion!";
// Save mission report to secure storage
File.WriteAllText("DeathStarMissionReport.txt", missionReport);
Console.WriteLine("Mission report saved to secure rebel database!");
// Verify file exists (security check)
if (File.Exists("DeathStarMissionReport.txt"))
{
Console.WriteLine("File successfully stored in rebel archives");
// Read back the report (för verification)
string storedReport = File.ReadAllText("DeathStarMissionReport.txt");
Console.WriteLine("\n=== STORED MISSION REPORT ===");
Console.WriteLine(storedReport);
}
// Read file line by line (för detailed analysis)
Console.WriteLine("\n=== LINE-BY-LINE ANALYSIS ===");
string[] reportLines = File.ReadAllLines("DeathStarMissionReport.txt");
int lineNumber = 1;
foreach (string line in reportLines)
{
Console.WriteLine($"Line {lineNumber}: {line}");
if (line.Contains("SUCCESS"))
{
Console.WriteLine(" *** MISSION SUCCESS CONFIRMED ***");
}
else if (line.Contains("Luke Skywalker"))
{
Console.WriteLine(" *** KEY PILOT IDENTIFIED ***");
}
lineNumber++;
}
// Append additional intelligence (ongoing operations)
string additionalIntel = "\n\nUPDATE: Imperial retaliation expected\nRecommendation: Evacuate Yavin base immediately\nNew base location: Hoth system";
File.AppendAllText("DeathStarMissionReport.txt", additionalIntel);
Console.WriteLine("\nAdditional intelligence appended to report");
// Create pilot roster file (för fleet management)
List<string> pilotRoster = new List<string>
{
"Luke Skywalker - Red Five - Force User: Yes",
"Wedge Antilles - Red Two - Survival Rate: 100%",
"Biggs Darklighter - Red Three - Status: KIA",
"Jek Porkins - Red Six - Status: KIA"
};
Console.WriteLine("\n=== CREATING PILOT ROSTER FILE ===");
File.WriteAllLines("RedSquadronRoster.txt", pilotRoster);
Console.WriteLine("Red Squadron roster saved to rebel personnel files");
Practical Example - Comprehensive Rebel Management System
public class RebelAgent
{
public string Name { get; set; }
public string CodeName { get; set; }
public string Homeworld { get; set; }
public int SkillLevel { get; set; }
public bool IsForceUser { get; set; }
public List<string> Specialties { get; set; }
public DateTime JoinDate { get; set; }
public RebelAgent()
{
Specialties = new List<string>();
JoinDate = DateTime.Now;
}
public override string ToString()
{
string forceStatus = IsForceUser ? "Force User" : "Non-Force User";
string specialtiesList = Specialties.Count > 0 ? string.Join(", ", Specialties) : "General Operations";
return $"{Name} ('{CodeName}') från {Homeworld} - {forceStatus}\n" +
$" Skill: {SkillLevel}/100 | Specialties: {specialtiesList}\n" +
$" Service Since: {JoinDate:yyyy-MM-dd}";
}
}
public class RebelDatabase
{
private List<RebelAgent> agents = new List<RebelAgent>();
private Random random = new Random();
public void AddAgent(string name, string codeName, string homeworld, int skillLevel, bool isForceUser)
{
RebelAgent newAgent = new RebelAgent
{
Name = name,
CodeName = codeName,
Homeworld = homeworld,
SkillLevel = skillLevel,
IsForceUser = isForceUser
};
// Auto-assign specialties based on abilities
if (isForceUser)
{
newAgent.Specialties.Add("Force Operations");
newAgent.Specialties.Add("Jedi Training");
}
if (skillLevel >= 90)
{
newAgent.Specialties.Add("Elite Combat");
newAgent.Specialties.Add("Special Operations");
}
else if (skillLevel >= 75)
{
newAgent.Specialties.Add("Advanced Combat");
}
if (homeworld == "Alderaan")
{
newAgent.Specialties.Add("Diplomatic Operations");
}
else if (homeworld == "Corellia")
{
newAgent.Specialties.Add("Piloting");
newAgent.Specialties.Add("Smuggling");
}
agents.Add(newAgent);
Console.WriteLine($"Agent {name} ('{codeName}') recruited to the Rebellion!");
}
public void ShowAllAgents()
{
Console.WriteLine("\n=== COMPLETE REBEL AGENT ROSTER ===");
Console.WriteLine($"Total Active Agents: {agents.Count}");
Console.WriteLine();
if (agents.Count == 0)
{
Console.WriteLine("No agents currently in database.");
Console.WriteLine("The Rebellion needs recruits!");
return;
}
for (int i = 0; i < agents.Count; i++)
{
Console.WriteLine($"AGENT #{i + 1}:");
Console.WriteLine(agents[i]);
Console.WriteLine(new string('-', 50));
}
}
public void SearchAgentsBySpecialty(string specialty)
{
Console.WriteLine($"\n=== AGENTS WITH '{specialty.ToUpper()}' SPECIALTY ===");
bool foundAny = false;
foreach (RebelAgent agent in agents)
{
if (agent.Specialties.Any(s => s.ToLower().Contains(specialty.ToLower())))
{
Console.WriteLine($"✓ {agent.Name} ('{agent.CodeName}') - Skill: {agent.SkillLevel}/100");
foundAny = true;
}
}
if (!foundAny)
{
Console.WriteLine($"No agents found med '{specialty}' specialty.");
Console.WriteLine("Consider recruiting specialists för this area!");
}
}
public void AssignRandomMission()
{
if (agents.Count == 0)
{
Console.WriteLine("Cannot assign mission: No agents available!");
return;
}
Console.WriteLine("\n=== RANDOM MISSION ASSIGNMENT ===");
// Select random agent
int randomIndex = random.Next(agents.Count);
RebelAgent selectedAgent = agents[randomIndex];
// Generate random mission based on agent abilities
List<string> possibleMissions = new List<string>();
if (selectedAgent.IsForceUser)
{
possibleMissions.Add("Infiltrate Imperial Facility using Force abilities");
possibleMissions.Add("Rescue Force-sensitive individuals från Imperial custody");
possibleMissions.Add("Investigate Sith artifacts för intelligence");
}
if (selectedAgent.SkillLevel >= 85)
{
possibleMissions.Add("Assassinate high-value Imperial target");
possibleMissions.Add("Lead covert operations team");
possibleMissions.Add("Train new rebel recruits");
}
if (selectedAgent.Specialties.Contains("Piloting"))
{
possibleMissions.Add("Lead starfighter assault mission");
possibleMissions.Add("Transport VIP through dangerous territory");
possibleMissions.Add("Reconnaissance flyby of Imperial installations");
}
possibleMissions.Add("Gather intelligence on Imperial troop movements");
possibleMissions.Add("Establish new rebel cell på distant world");
possibleMissions.Add("Sabotage Imperial supply convoy");
string selectedMission = possibleMissions[random.Next(possibleMissions.Count)];
Console.WriteLine($"AGENT SELECTED: {selectedAgent.Name} ('{selectedAgent.CodeName}')");
Console.WriteLine($"MISSION: {selectedMission}");
Console.WriteLine($"AGENT SUITABILITY: {(selectedAgent.SkillLevel >= 75 ? "HIGH" : "MODERATE")}");
if (selectedAgent.IsForceUser && selectedMission.Contains("Force"))
{
Console.WriteLine("SPECIAL: Force abilities directly relevant to mission success!");
}
Console.WriteLine("May the Force be with you på this mission!");
}
public void GenerateStatistics()
{
if (agents.Count == 0)
{
Console.WriteLine("No statistics available - no agents i database.");
return;
}
Console.WriteLine("\n=== REBEL ALLIANCE STATISTICS ===");
int forceUsers = agents.Count(a => a.IsForceUser);
double averageSkill = agents.Average(a => a.SkillLevel);
var topAgent = agents.OrderByDescending(a => a.SkillLevel).First();
Console.WriteLine($"Total Agents: {agents.Count}");
Console.WriteLine($"Force Users: {forceUsers} ({(double)forceUsers / agents.Count * 100:F1}%)");
Console.WriteLine($"Average Skill Level: {averageSkill:F1}/100");
Console.WriteLine($"Top Agent: {topAgent.Name} (Skill: {topAgent.SkillLevel}/100)");
// Homeworld analysis
var homeworldGroups = agents.GroupBy(a => a.Homeworld);
Console.WriteLine("\nRECRUITMENT BY HOMEWORLD:");
foreach (var group in homeworldGroups.OrderByDescending(g => g.Count()))
{
Console.WriteLine($" {group.Key}: {group.Count()} agents");
}
// Skill level distribution
int elite = agents.Count(a => a.SkillLevel >= 90);
int advanced = agents.Count(a => a.SkillLevel >= 75 && a.SkillLevel < 90);
int standard = agents.Count(a => a.SkillLevel >= 50 && a.SkillLevel < 75);
int novice = agents.Count(a => a.SkillLevel < 50);
Console.WriteLine("\nSKILL LEVEL DISTRIBUTION:");
Console.WriteLine($" Elite (90+): {elite} agents");
Console.WriteLine($" Advanced (75-89): {advanced} agents");
Console.WriteLine($" Standard (50-74): {standard} agents");
Console.WriteLine($" Novice (<50): {novice} agents");
}
}
// Usage example - Building the Rebel Alliance database
Console.WriteLine("=== INITIALIZING REBEL ALLIANCE DATABASE ===");
RebelDatabase rebelDB = new RebelDatabase();
// Add key rebellion figures
rebelDB.AddAgent("Luke Skywalker", "Red Five", "Tatooine", 85, true);
rebelDB.AddAgent("Leia Organa", "Princess", "Alderaan", 90, true);
rebelDB.AddAgent("Han Solo", "Captain", "Corellia", 88, false);
rebelDB.AddAgent("Wedge Antilles", "Red Two", "Corellia", 95, false);
rebelDB.AddAgent("Mon Mothma", "Supreme Commander", "Chandrila", 92, false);
// Show all agents
rebelDB.ShowAllAgents();
// Search by specialty
rebelDB.SearchAgentsBySpecialty("Force");
rebelDB.SearchAgentsBySpecialty("Piloting");
// Random mission assignment
rebelDB.AssignRandomMission();
rebelDB.AssignRandomMission();
// Generate statistics
rebelDB.GenerateStatistics();
Mathematical Operations - Tactical Calculations
Console.WriteLine("=== REBEL TACTICAL CALCULATIONS ===");
// Distance calculations (för hyperspace jumps)
double tatooineToDagobah = Math.Sqrt(Math.Pow(12.5, 2) + Math.Pow(8.3, 2));
Console.WriteLine($"Hyperspace distance Tatooine to Dagobah: {Math.Round(tatooineToDagobah, 2)} parsecs");
// Resource calculations
int rebelCredits = 50000;
int imperialCredits = -25000; // Debt från stolen supplies
Console.WriteLine($"Rebel treasury: {Math.Abs(rebelCredits)} credits (positive)");
Console.WriteLine($"Imperial debt: {Math.Abs(imperialCredits)} credits (amount owed to us)");
// Power calculations (Death Star vs Rebel fleet)
double deathStarPower = Math.Pow(10, 15); // Massive power
double rebelFleetPower = Math.Pow(2, 20); // Much smaller
Console.WriteLine($"Death Star power: {deathStarPower:E} units");
Console.WriteLine($"Combined Rebel fleet: {rebelFleetPower:E} units");
Console.WriteLine($"Power ratio (Death Star advantage): {Math.Round(deathStarPower / rebelFleetPower, 0):N0}:1");
// Mission success probability calculations
double pilotSkill = 85.5;
double shipCondition = 92.3;
double forceBonus = 15.0; // Luke gets Force bonus
double baseProbability = (pilotSkill + shipCondition) / 2;
double finalProbability = Math.Min(baseProbability + forceBonus, 100); // Cap at 100%
Console.WriteLine($"\n=== DEATH STAR TRENCH RUN PROBABILITY ===");
Console.WriteLine($"Base success rate: {Math.Round(baseProbability, 1)}%");
Console.WriteLine($"With Force bonus: {Math.Round(finalProbability, 1)}%");
if (finalProbability >= 80)
Console.WriteLine("HIGH SUCCESS PROBABILITY - Proceed med attack!");
else
Console.WriteLine("RISKY MISSION - Consider alternative strategies");
// Fleet formation calculations
int totalPilots = 30;
int squadronSize = 12;
int completeSquadrons = totalPilots / squadronSize;
int remainingPilots = totalPilots % squadronSize;
Console.WriteLine($"\n=== FLEET ORGANIZATION ===");
Console.WriteLine($"Total available pilots: {totalPilots}");
Console.WriteLine($"Complete squadrons: {completeSquadrons}");
Console.WriteLine($"Pilots för partial squadron: {remainingPilots}");
Coding Best Practices - The Rebel Way
1. Clear Variable Names (Like clear rebel communications)
// BAD - Cryptic som Imperial codes
int x = 25;
List<string> l = new List<string>();
bool b = false;
// GOOD - Clear som rebel communications
int pilotAge = 25;
List<string> availablePilots = new List<string>();
bool isMissionSuccessful = false;
// EXCELLENT - Context-aware naming
int lukeSkywalkerAge = 19;
List<string> redSquadronPilots = new List<string>();
bool deathStarDestroyedSuccessfully = true;
2. Break Down Complex Operations (Like organizing rebel cells)
// BAD - Monolithic operation (like Imperial command structure)
public void HandleRebelOperations()
{
// 100 lines of mixed code doing everything...
// Loading pilots, planning missions, executing attacks, generating reports
// This becomes unmanageable som Imperial bureaucracy!
}
// GOOD - Modular approach (like rebel cell structure)
public void HandleRebelOperations()
{
List<RebelPilot> pilots = LoadAvailablePilots();
List<Mission> missions = PlanTacticalMissions(pilots);
List<MissionResult> results = ExecuteMissions(missions);
GenerateBattleReports(results);
UpdateFleetStatus(pilots, results);
}
private List<RebelPilot> LoadAvailablePilots()
{
// Focused on just loading pilot data
return new List<RebelPilot>();
}
private List<Mission> PlanTacticalMissions(List<RebelPilot> pilots)
{
// Focused on just mission planning
return new List<Mission>();
}
3. Meaningful Comments (Strategic intelligence, inte obvious facts)
// BAD - Obvious comments (like stating obvious tactical facts)
int pilotCount = 12; // Set pilot count to 12
bool isReady = true; // Set ready status to true
// GOOD - Strategic context (like important tactical notes)
int pilotCount = 12; // Red Squadron standard strength för Death Star assault
bool isReady = true; // All systems check complete - cleared för lightspeed
// EXCELLENT - Critical intelligence
int exhauustPortDiameter = 2; // Critical vulnerability - exact targeting required
bool targetingComputerActive = false; // Luke will use Force instead - confirmed strategy
Sammanfattning (Your Complete Rebel Arsenal)
- Lists provide dynamic fleet management (expandable som the growing Rebellion)
- String methods help decrypt och analyze Imperial communications
- DateTime coordinates mission timing och historical events
- TryParse safely handles potentially corrupted rebel transmissions
- Random simulates tactical variety och unpredictable scenarios
- File operations secure critical rebel data för future operations
- Math functions calculate tactical advantages och mission probabilities
- Good practices make your code som organized som efficient rebel cells
Remember: “Size matters not. Look at me. Judge me by my size, do you?” - Yoda. Clean, well-organized code might look simple, men it’s incredibly powerful. A small, well-structured program can accomplish som much som Luke destroying the Death Star!
Your Rebel Arsenal is now complete, young Padawan! Du har alla tools needed för building real galactic applications. Start med small programs och gradually take on bigger challenges. Soon you’ll be ready för your own coding Death Star runs!
The Rebellion’s success depends on organizing data, making smart decisions, och using the right tools för each mission. Now go forth och code som a true rebel!
May the Code be with you, always!
Föregående: Kapitel 4 - If-satser och loopar: The Tactical Decisions
The Journey Continues…
“The Force will be with you, always.” - Obi-Wan Kenobi
Young Padawan, you have completed your initial training i The Ways of C-Sharp. Du har learned:
- The Force of Data - Variables och types
- The Jedi Arts - Methods och functions
- Building the Rebel Alliance - Classes och objects
- The Tactical Decisions - Control flow och logic
- The Rebel Arsenal - Practical tools och techniques
Men som Yoda would say: “Truly wonderful, the mind of a child is.” Your journey i programming has just begun. There are still many mysteries to explore - advanced OOP, databases, web development, mobile apps, och more.
Keep practicing, keep building, och remember: every expert was once a beginner who refused to give up. The Force is strong med this one!
May your code be bug-free och your apps be successful!
Signed, The Rebel Alliance Programming Academy “Learn you will, how to code like a Jedi!”