Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Csharp exercise
RPG inventory
Sign in to hand in your solution and get feedback.
// RPG inventory program
using System;
using System.Collections.Generic;
class Submission
{
// -------------------------
// Subprograms
// -------------------------
static void add_item(List<string> inventory)
{
Console.WriteLine("What item are you adding to your inventory?");
string item = Console.ReadLine();
inventory.Add(item);
Console.WriteLine("Item added.");
}
static void search(List<string> inventory)
{
Console.WriteLine("What item do you want to see if you have?");
string item = Console.ReadLine();
if (inventory.Contains(item))
{
Console.WriteLine("You have the item.");
}
else
{
Console.WriteLine($"You do not have a {item}");
}
}
static void drop_item(List<string> inventory)
{
Console.WriteLine("What item do you want to drop?");
string item = Console.ReadLine();
// Check item exists
if (inventory.Contains(item))
{
inventory.Remove(item);
Console.WriteLine("Item dropped.");
}
else
{
Console.WriteLine("You do not have this item.");
}
}
static void look(List<string> inventory)
{
Console.WriteLine("Which inventory slot do you want to look at?");
int slot = Convert.ToInt32(Console.ReadLine());
if (slot < inventory.Count) {
Console.WriteLine($"You have a {inventory[slot]} in slot {slot}");
}
else
{
Console.WriteLine("Invalid slot.");
}
}
// Returns false when the player chooses to quit.
static bool choose_action(List<string> inventory)
{
Console.WriteLine($"You have {inventory.Count} items in your inventory.");
Console.WriteLine("What action do you want to take? (add/look/drop/search/quit)");
string action = Console.ReadLine();
switch (action)
{
case "add":
add_item(inventory);
break;
case "drop":
drop_item(inventory);
break;
case "look":
look(inventory);
break;
case "search":
search(inventory);
break;
case "quit":
return false;
}
Console.WriteLine();
return true;
}
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
List<string> inventory = new List<string>() {"sword", "shield"};
while (choose_action(inventory)) {
}
}
}