Creating a player character.
★☆☆Role playing games require players to adopt a virtual character in the game. Characters often have traits recorded as numerical values for strength, dexterity, constitution, intelligence, wisdom and charisma. This program creates a simple character and saves it to a file.
Write a program that asks the user to enter the name of a character, together with their health, attack and defend as numbers. The program should write the data to a file.
Remember to add a comment before a subprogram, selection or iteration statement to explain its purpose.
make_character that:[name, health, attack, defend].save_character that:attribute=value (for example health=10).make_character and save_character subprograms are called.Enter the name of the character:
Elf
Enter health:
10
Enter attack:
13
Enter defend:
8
Character saved.
Elf.txt file would then contain:[Name]
Elf
[Attributes]
health=10
attack=13
defend=8
make_character
// Input the attributes for the character
static string[] make_character()
{
---
Console.WriteLine("Enter the name of the character:");
string character_name = Console.ReadLine();
string health = "";
string attack = "";
string defend = "";
---
// Ensure stats are numbers
while (!is_only_digits(health))
{
Console.WriteLine("Enter health:");
health = Console.ReadLine();
}
---
while (!is_only_digits(attack))
{
Console.WriteLine("Enter attack:");
attack = Console.ReadLine();
}
---
while (!is_only_digits(defend))
{
Console.WriteLine("Enter defend:");
defend = Console.ReadLine();
}
---
// Build the return list
string[] attributes = { character_name, health, attack, defend };
return attributes;
}
is_only_digits
// Check if a string comprises of only digits
static bool is_only_digits(string value)
{
---
bool result = value.Length > 0;
foreach (char c in value)
{
---
if (!char.IsDigit(c))
{
result = false;
}
---
}
return result;
}
save_character
// Save the character to a file
static void save_character(string[] attributes)
{
---
string file_name = attributes[0] + ".txt";
StreamWriter file = new StreamWriter(file_name);
---
// Name section
file.WriteLine("[Name]");
string character_name = attributes[0];
file.WriteLine(character_name);
file.WriteLine();
---
// Stats section
file.WriteLine("[Attributes]");
string health = "health=" + attributes[1];
file.WriteLine(health);
string attack = "attack=" + attributes[2];
file.WriteLine(attack);
string defend = "defend=" + attributes[3];
file.WriteLine(defend);
file.Close();
---
}