Game Score Tracker C#
👤 Sharing: AI
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class GameScoreTracker
{
private Dictionary<string, int> playerScores;
public GameScoreTracker()
{
playerScores = new Dictionary<string, int>();
}
public void AddPlayer(string playerName)
{
if (!playerScores.ContainsKey(playerName))
{
playerScores[playerName] = 0;
Console.WriteLine($"Player '{playerName}' added.");
}
else
{
Console.WriteLine($"Player '{playerName}' already exists.");
}
}
public void UpdateScore(string playerName, int scoreChange)
{
if (playerScores.ContainsKey(playerName))
{
playerScores[playerName] += scoreChange;
Console.WriteLine($"Score updated for '{playerName}'. New score: {playerScores[playerName]}");
}
else
{
Console.WriteLine($"Player '{playerName}' not found.");
}
}
public void DisplayScores()
{
if (playerScores.Count == 0)
{
Console.WriteLine("No players in the game.");
return;
}
Console.WriteLine("Current Scores:");
foreach (var player in playerScores.OrderByDescending(x => x.Value))
{
Console.WriteLine($"{player.Key}: {player.Value}");
}
}
public string GetWinner()
{
if (playerScores.Count == 0)
{
return "No players in the game.";
}
var winner = playerScores.OrderByDescending(x => x.Value).FirstOrDefault();
return $"The winner is '{winner.Key}' with a score of {winner.Value}!";
}
public static void Main(string[] args)
{
GameScoreTracker tracker = new GameScoreTracker();
while (true)
{
Console.WriteLine("\nGame Score Tracker Menu:");
Console.WriteLine("1. Add Player");
Console.WriteLine("2. Update Score");
Console.WriteLine("3. Display Scores");
Console.WriteLine("4. Get Winner");
Console.WriteLine("5. Exit");
Console.Write("Enter your choice: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
Console.Write("Enter player name: ");
string playerName = Console.ReadLine();
tracker.AddPlayer(playerName);
break;
case "2":
Console.Write("Enter player name: ");
string updatePlayerName = Console.ReadLine();
Console.Write("Enter score change: ");
if (int.TryParse(Console.ReadLine(), out int scoreChange))
{
tracker.UpdateScore(updatePlayerName, scoreChange);
}
else
{
Console.WriteLine("Invalid score change. Please enter a number.");
}
break;
case "3":
tracker.DisplayScores();
break;
case "4":
Console.WriteLine(tracker.GetWinner());
break;
case "5":
Console.WriteLine("Exiting...");
return;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}
}
```
👁️ Viewed: 9
Comments