Loading...
OsmanK avatar OsmanK 0 Точки

Problem 3. Heroes of Code and Logic VII

https://pastebin.com/WHb2XVAU

 

  • Programming Fundamentals Final Exam 04.04.2020
    Problem 3. Heroes of Code and Logic VII
    You got your hands on the most recent update on the best MMORPG of all time – Heroes of Code and Logic. You want to play it all day long! So cancel all other arrangements and create your party!
    
    On the first line of the standard input you will receive an integer n – the number of heroes that you can choose for your party. On the next n lines, the heroes themselves will follow with their hit points and mana points separated by empty space in the following format: 
    {hero name} {HP} {MP} 
    -	where HP stands for hit points and MP for mana points
    -	a hero can have a maximum of 100 HP and 200 MP
    After you have successfully picked your heroes, you can start playing the game.  You will be receiving different commands, each on a new line, separated by " – ", until the "End" command is given. 
    There are several actions that can be performed by the heroes:
    CastSpell – {hero name} – {MP needed} – {spell name} 
    •	If the hero has the required MP, he casts the spell, thus reducing his MP. Print this message: 
    o	"{hero name} has successfully cast {spell name} and now has {mana points left} MP!"
    •	If the hero is unable to cast the spell print:
    o	"{hero name} does not have enough MP to cast {spell name}!"
    TakeDamage – {hero name} – {damage} – {attacker}
    •	Reduce the hero HP by the given damage amount. If the hero is still alive (his HP is greater than 0) print:
    o	"{hero name} was hit for {damage} HP by {attacker} and now has {current HP} HP left!"
    •	If the hero has died, remove him from your party and print:
    o	"{hero name} has been killed by {attacker}!"
    Recharge – {hero name} – {amount}
    •	The hero increases his MP. If a command is given that would bring the MP of the hero above 200, MP is increased so that it reaches the maximum. Print the following message:
    o	"{hero name} recharged for {amount recovered} MP!"
    Heal – {hero name} – {amount}
    •	The hero increases his HP. If a command is given that would bring the HP of the hero above 100, HP is increased so that it reaches the maximum. Print the following message:
    o	"{hero name} healed for {amount recovered} HP!"
    Input
    •	On the first line of the standard input you will receive an integer n
    •	On the next n lines, the heroes themselves will follow with their hit points and mana points separated by empty space in the following format
    •	You will be receiving different commands, each on a new line, separated by " – ", until the "End" command is given
    Output
    •	Print all members of your party who are still alive, sorted by their HP in descending order, then by their name in ascending order, in the following format (their HP/MP need to be indented 2 spaces):
    "{hero name}
     	 HP: {current HP}
     MP: {current MP}
     ..."
    Constraints
    •	The starting HP/MP of the heroes will be valid, 32-bit integers, will never be negative or exceed the respective limits.
    •	The HP/MP amounts in the commands will never be negative.
    •	The hero names in the commands will always be valid members of your party. No need to check that explicitly
    Examples
    Input	Output
    2
    Solmyr 85 120
    Kyrre 99 50
    Heal - Solmyr - 10
    Recharge - Solmyr - 50
    TakeDamage - Kyrre - 66 - Orc
    CastSpell - Kyrre - 15 - ViewEarth
    End	Solmyr healed for 10 HP!
    Solmyr recharged for 50 MP!
    Kyrre was hit for 66 HP by Orc and now has 33 HP left!
    Kyrre has successfully cast ViewEarth and now has 35 MP!
    Solmyr
      HP: 95
      MP: 170
    Kyrre
      HP: 33
      MP: 35
    Comments
    These are examples of successful actions. The different colors denote the commands and their respective messages.
    Input	Output
    4
    Adela 90 150
    SirMullich 70 40
    Ivor 1 111
    Tyris 94 61
    Heal - SirMullich - 50
    Recharge - Adela - 100
    CastSpell - Tyris - 1000 - Fireball
    TakeDamage - Tyris - 99 - Fireball
    TakeDamage - Ivor - 3 - Mosquito
    End	SirMullich healed for 30 HP!
    Adela recharged for 50 MP!
    Tyris does not have enough MP to cast Fireball!
    Tyris has been killed by Fireball!
    Ivor has been killed by Mosquito!
    SirMullich
      HP: 100
      MP: 40
    Adela
      HP: 90
      MP: 200
    Comments
    Heal – SirMullich healed for 30 HP due to the HP max limit.
    Recharge – Adela recharged for 50 MP due to the MP max limit.
    CastSpell – Tyris does not have enough MP to cast the spell.
    TakeDamage – Tyris`s HP is reduced by 99, thus becoming -5, which means that he is dead.
    TakeDamage – Ivor`s HP is now -2, so he is dead too.
    After the "End" command we print the remaining living heroes, sorted by their HP in reverse order.
    

    Когато тествам решението Heal - Solmyr - 10 то зарежда с 15, вместо 10. Не можах да намеря грешката.

  •  

Тагове:
0
Fundamentals Module
Drinka avatar Drinka 29 Точки

Мисля, че самите проверки за hp-то и mp-to са грешни. heroes[heroName]["hp"] + neededHp винаги ще е повече от heroes[heroName]["hp"], защото прибавяш някакво число към променливата. Проверката би трябвало да е if(heroes[heroName]["hp"] + neededHp >100){...}, съответно за mp- if (heroes[heroName]["mp"] + rechargeMp > 200) {...}

0
daniel123123 avatar daniel123123 27 Точки

C# 100/100

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
class Program {
    static void Main() {
        var heroes = new Dictionary<string, Hero>();
        for (int n = int.Parse(Console.ReadLine()); n > 0; --n) {
            var data = Console.ReadLine().Split(" ");
            heroes[data[0]] = new Hero(int.Parse(data[1]), int.Parse(data[2]));
        }
        var str = "";
        while ((str = Console.ReadLine()) != "End") {
            var data = str.Split(" - ");
            if (data[0] == "CastSpell") {
                var name = data[1];
                int needed = int.Parse(data[2]);
                var spell = data[3];
                if (heroes[name].Mp >= needed) {
                    heroes[name].Mp -= needed;
                    Console.WriteLine($"{name} has successfully cast {spell} and now has {heroes[name].Mp} MP!");
                } else Console.WriteLine($"{name} does not have enough MP to cast {spell}!");
            }
            if (data[0] == "TakeDamage") {
                var name = data[1];
                int dmg = int.Parse(data[2]);
                var att = data[3];
                heroes[name].Hp -= dmg;
                if (heroes[name].Hp > 0) Console.WriteLine($"{name} was hit for {dmg} HP by {att} and now has {heroes[name].Hp} HP left!");
                else {
                    heroes.Remove(name);
                    Console.WriteLine($"{name} has been killed by {att}!");
                }
            }
            if (data[0] == "Recharge") {
                var name = data[1];
                int amount = int.Parse(data[2]);
                int oldMp = heroes[name].Mp;
                heroes[name].Mp += amount;
                if (heroes[name].Mp > 200) heroes[name].Mp = 200;
                Console.WriteLine($"{name} recharged for {heroes[name].Mp - oldMp} MP!");
            }
            if (data[0] == "Heal") {
                var name = data[1];
                int amount = int.Parse(data[2]);
                int oldHp = heroes[name].Hp;
                heroes[name].Hp += amount;
                if (heroes[name].Hp > 100) heroes[name].Hp = 100;
                Console.WriteLine($"{name} healed for {heroes[name].Hp - oldHp} HP!");
            }
        }
        Print(heroes);
    }
    static void Print(Dictionary<string, Hero> heroes) {
        foreach (var nameHero in heroes) {
            Console.WriteLine(nameHero.Key);
            Console.WriteLine("  HP: " + nameHero.Value.Hp);
            Console.WriteLine("  MP: " + nameHero.Value.Mp);
        }
    }
}
class Hero {
    public Hero(int hp, int mp) {
        Hp = hp;
        Mp = mp;
    }
    public int Hp { get; set; }
    public int Mp { get; set; }
}

 

1
clinkreindeer avatar clinkreindeer 1 Точки

I've also heard of teachers requiring students to annotate each line of code. While this may be a reasonable policy for extreme novices, such remarks are akin to training wheels and should be removed when bicycling with more experienced mini crossword

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.