如何走出这个循环?

时间:2017-03-09 13:57:17

标签: c# cycle

一天中的所有时间!问题是循环:用最后2行写代码被定义为无法访问的代码,因为当你按任何键的情况下开始无限循环。编程经验很少,也不理解。如何走出这个循环?这是该计划的代码:

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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你必须查询里面的循环:

while (true)
{
    keypress = Console.ReadKey(); // continuously check for key presses
    switch (keypress.KeyChar) // process new keypresses
    {
        case 'A':
...

并且不要忘记在某个时刻打破循环(例如,当满足某些条件或按下某个键时):

...

    if(endCondition)
        break; // will exit while(true)
}

答案 1 :(得分:0)

嗯,总是有break命令。您可以标记在按下某个键后,您想要中断。然后在switch之外,你break。但是,为什么还需要while(true)循环?