Search code examples
c#cycle

How to get out of this cycle?


All kind time of day! The question is the cycle: write code with the last 2 lines are defined as unreachable code, because when you press any key of the case starts an infinite loop. Experience in programming is little and does not understand. How to get out of this cycle? Here's the code of the program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace ConsoleApplication3
    {
    class Hero
    {
        public int x = 0;
        public int y = 0;
        public int hp = 3;
        public double power = 3;
        public void printHero()
        {
            Console.WriteLine(" x={0},y={1},hp={2},power={3}", x, y, hp, power);
        }
        public void hitHero()
        {
            hp = hp - 1;
        }
        public void attackHero()
        {
            power = power - 0.5;
        }
        static void Main(string[] args)
        {
            Hero hero;
            hero = new Hero();
            ConsoleKeyInfo keypress;
            keypress = Console.ReadKey();
            while (true)
            {
                switch (keypress.KeyChar)
                {
                    case 'A':
                        hero.x = hero.x - 1;
                        hero.printHero();
                        break;
                    case 'D':
                        hero.x = hero.x +1;
                        hero.printHero();
                        break;
                    case 'W':
                        hero.y = hero.y + 1;
                        hero.printHero();
                        break;
                    case 'S':
                        hero.y = hero.y - 1;
                        hero.printHero();
                        break;
                    case 'E':
                        hero.attackHero();
                        hero.printHero();
                        break;
                    case 'X':
                        hero.hitHero();
                        hero.printHero();
                        break;
                    default:
                        break;
                }
            } 
            Console.ReadLine();
            return;
        }
    }
}

Solution

  • Well, there's always the break command. You can flag that after a key has been pushed, you want to break. And then outside the switch, you break. However, why do you need to have a while(true) loop anyway?