> 일반배열

   string[] testList = new string[10];
            testList[0] = "일";
            testList[1] = "이";

            foreach (string item in testList)
            {
                int index = Array.IndexOf( testList, item ); 
            }

 

> Item.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class Item
    {
        public string name;

        public Item(string name)
        {
            this.name = name;
            Console.WriteLine($"아이템 {this.name}이 생성되었습니다.");
        }
    }
}

 

> Inventory.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class Inventory
    {
        public Item[] items;
        int itemIndex = 0;

        public Inventory(int capacity)
        {
            items = new Item[capacity];
            Console.WriteLine("인벤토리가 생성되었습니다.");
        }

        public void AddItem(Item item)
        {
            if (this.itemIndex < this.items.Length)
            {
                this.items[this.itemIndex] = item;
                this.itemIndex++;
            }
        }

        public Item GetItem(String itemName)
        {
            Item item = null; // 꺼낸 아이템 저장
            Item[] tempArr = new Item[this.items.Length - 1];  // 꺼낸 아이템 정리용 임시 배열
            bool check = false;
            int delIndex = 0;

            for (int i = 0; i < this.items.Length; i++)
            {
                if (this.items[i] != null)
                {
                    // 검색대상 같은지 확인
                    if (itemName == this.items[i].name)
                    {
                        item = this.items[i];
                        delIndex = i;
                        check = true;
                    }
                    else
                    {
                        // 기존 배열에서 찾은 인덱스 확인하여 그 인덱스에, 다음 내용물 넣기
                        if (i > delIndex && check)
                        {
                            tempArr[i - 1] = this.items[i];
                        }
                        else
                        {
                            // 새로운 배열에 넣기
                            if (tempArr.Length > i)
                            {
                                tempArr[i] = this.items[i];
                            }
                        } //if end
                    } // else end
                } // if end
            } //for end

            // 내용물 찾아 꺼낸 경우 기존 배열 업데이트
            if (check)
            {
                this.items = tempArr;
                Console.WriteLine(item.name);
            }
            return item;
        }

        public Item FindItem(String itemName)
        {
            Item item = null;
            for (int i = 0; i < this.items.Length; i++)
            {
                if (this.items[i] != null)
                {
                    if (itemName == this.items[i].name)
                    {
                        Console.WriteLine(this.items[i].name);
                        item = this.items[i];
                        break;
                    }
                }
            }
            return item;
        }

        public int GetCount()
        {
            int itemCount = 0;
            foreach (Item item in this.items)
            {
                if (item != null)
                {
                    itemCount++;
                }
            }
            return itemCount;
        }

        public void PrintItemNames()
        {
            Console.WriteLine("> 전체 목록");

            /*  
             // forEach 순환문
             foreach (Item item in this.items)
              {
                  if (item == null)
                  {
                      Console.WriteLine("[  ]");
                  }
                  else
                  {
                      Console.WriteLine(item.name);
                  }
              }
             */


            for (int i = 0; i < this.items.Length; i++)
            {
                if (this.items[i] == null)
                {
                    Console.WriteLine("[  ]");
                }
                else
                {
                    Console.WriteLine($"({i}){this.items[i].name}");
                }
            }

        }
    }
}

 

> App.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class App
    {

        public App()
        {
            Inventory inventory = new Inventory(5);
            inventory.AddItem(new Item("장검"));
            inventory.AddItem(new Item("궁"));
            inventory.AddItem(new Item("투구"));
            inventory.AddItem(new Item("장화"));
            inventory.AddItem(new Item("벨트"));

            Console.WriteLine();

            // ㅡㅡㅡㅡㅡㅡ 가방내용 전체 출력 ㅡㅡㅡㅡㅡㅡ
            inventory.PrintItemNames();
            Console.WriteLine();

            // ㅡㅡㅡㅡㅡㅡ 특정 아이템 검색 ㅡㅡㅡㅡㅡㅡ
            Console.Write("> 검색: ");
            Item findedItem = inventory.FindItem("궁");
            if (findedItem == null) { 
                Console.WriteLine("찾는 아이템 없음");
            }
            else
            {
                Console.WriteLine($"[{findedItem.name}]을 찾았습니다.");
            }

            Console.WriteLine();

            //ㅡㅡㅡㅡㅡㅡ 찾아 꺼내기 ㅡㅡㅡㅡㅡㅡ
            Console.Write("> 꺼내기: ");
            Item getedItem = inventory.GetItem("장화");
            if (getedItem == null)
            {
                Console.WriteLine("> 꺼낼 아이템 없음");
            }
            else
            {
                Console.WriteLine($"[{getedItem.name}]을 꺼냈습니다.");
            }

            Console.WriteLine();
            inventory.PrintItemNames();
        }
    }
}

'c# 강의 > 과제' 카테고리의 다른 글

20200420 - List 과제  (0) 2020.04.20
20200417 - 주말과제(요리,레시피)  (0) 2020.04.19
20200414 - 테란~아카데미까지  (0) 2020.04.14
20200413 - 슈팅 게임  (0) 2020.04.13
20200413 - 팩토리 시즈모드  (0) 2020.04.13

 


> App.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class App
    {

        public App()
        {
            Inventory inventory = new Inventory(5);
            inventory.AddItem(new Item("장검"));
            inventory.AddItem(new Item("궁"));
            inventory.AddItem(new Item("투구"));
            inventory.AddItem(new Item("장화"));
            inventory.AddItem(new Item("벨트"));
            // inventory.AddItem(new Item("장검6"));
           
            Console.WriteLine();

            inventory.PrintItemNames();
            Console.WriteLine();

            Console.Write("[궁] 검색: ");
            Item findedItem = inventory.FindItem("궁");
            if (findedItem == null) { Console.WriteLine("찾는 아이템 없음"); }

            Console.WriteLine();

            Console.Write("[장화] 꺼내기: ");
            Item getedItem = inventory.GetItem("장화");
            if (getedItem == null)
            {
                Console.WriteLine("꺼낼 아이템 없음");
            }
            else
            {
                Console.WriteLine($"{getedItem.name}을 꺼냈습니다.");
            }

            Console.WriteLine();
            inventory.PrintItemNames();

        }
    }
}

 

> Inventory.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class Inventory
    {
        public Item[] items;
        int itemIndex = 0;

        public Inventory(int capacity)
        {
            items = new Item[capacity];
            Console.WriteLine("인벤토리가 생성되었습니다.");
        }

        public void AddItem(Item item)
        {
            if (this.itemIndex < this.items.Length)
            {
                this.items[this.itemIndex] = item;
                this.itemIndex++;
            }
        }

        public Item GetItem(String itemName)
        {
            Item item = null;

            for (int i = 0; i < this.items.Length; i++)
            {
                if (this.items[i] != null)
                {
                    if (itemName == this.items[i].name)
                    {
                        item = this.items[i];
                        this.items[i] = null;
                    }
                }
            }
            return item;
        }

        public Item FindItem(String itemName)
        {
            Item item = null;
            for (int i = 0; i < this.items.Length; i++)
            {
                if (this.items[i] != null)
                {
                    if (itemName == this.items[i].name)
                    {
                        Console.WriteLine(this.items[i].name);
                        item = this.items[i];
                        break;
                    }
                }
            }
            return item;
        }

        public int GetCount()
        {
            int itemCount = 0;
            foreach (Item item in this.items)
            {
                if (item != null)
                {
                    itemCount++;
                }
            }
            return itemCount;
        }

        public void PrintItemNames()
        {
            foreach (Item item in this.items)
            {
                if (item == null)
                {
                    Console.WriteLine("[  ]");
                }
                else
                {
                    Console.WriteLine(item.name);
                }
            }

            /*
                 for (int i = 0; i < this.items.Length; i++)
                {
                    Console.WriteLine(this.items[i].name);
                }
            */
        }
    }
}

 

> Item.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414_array
{
    class Item
    {
        public string name;

        public Item(string name)
        {
            this.name = name;
            Console.WriteLine($"아이템 {this.name}이 생성되었습니다.");
        }
    }
}

 


> App.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414
{
    class App
    {
        bool isBarracks;
        bool isAcademy;


        public App()
        {


            Barracks barracks = new Barracks();
            barracks.Init(1001, 1000); // 초기화 - ID / HP
            this.isBarracks = true;

            LiftOffState state = barracks.GetLiftOffState();

            barracks.Move();
            barracks.Stop();
            barracks.ChangeLiftOffState();
            barracks.Move();
            barracks.Stop();

            barracks.ChangeLiftOffState();
            barracks.Move();
            barracks.Stop();

            Console.WriteLine();


            // 캐릭터 생성
            if (this.isBarracks)
            {
                Unit marine = barracks.CreateUnit(UnitType.Marine);

                marine.Attack(barracks);

                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("마린을 생성하려면 배럭이 필요합니다.");
            }

           

            // 아카데미 생성
            if (isBarracks)
            {
                Academy academy = new Academy();
                academy.Init(2001, 600);
                this.isAcademy = true;
            }
            else
            {
                Console.WriteLine("아카데미를 생성하려면 배럭스가 필요합니다.");
            }

            // 파이어뱃 생성
            if (isAcademy)
            {
                Unit medic = barracks.CreateUnit(UnitType.Medic);
                Unit firebat = barracks.CreateUnit(UnitType.Firebat);
            }
            else
            {
                Console.WriteLine("파이어베이스를 생성하려면 아카데미가 필요합니다.");
            }
        }
    }
}

 

> Unit.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414
{
    public enum UnitType
    {
        Marine, Medic, Firebat, Ghost
    }

    class Unit
    {
        UnitType unitType;
        int damage;
        int hp;

        public Unit(UnitType unitType, int damage, int hp)
        {
            this.unitType = unitType;
            this.damage = damage;
            this.hp = hp;

            Console.WriteLine($"{this.unitType} / {this.damage} / {this.hp} 생성");
        }

        public void Attack(Barracks target)
        {
            Console.WriteLine($"[{GetUnitType()}]이(가) [{target.name}]을 공격합니다.");
            target.Hit(this, this.damage);
        }

        public UnitType GetUnitType()
        {
            return this.unitType;
        }
    }
}

> Barracks.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414
{
    enum LiftOffState
    {
        LiftOff,
        Land
    }

    class Barracks
    {
        //멤버 변수
        public int id;
        public string name; //이름
        public int maxHp; //체력
        public int hp;
        public LiftOffState liftOffState; // 떠있는 상태


        //생성자
        public Barracks()
        {
            Console.WriteLine("배럭스가 생성되었습니다.");
            this.liftOffState = LiftOffState.Land;
            this.name = "배럭스";
        }

        // 초기화 ID / HP
        public void Init(int id, int maxHp)
        {
            this.id = id;
            this.maxHp = maxHp;
            this.hp = this.maxHp;
        }

        //상태를 변경할수 있다.
        public void ChangeLiftOffState()
        {
            if (GetLiftOffState() == LiftOffState.Land)
            {
                LiftOff();
            }
            else if (GetLiftOffState() == LiftOffState.LiftOff)
            {
                Land();
            }
        }

        //이동
        public void Move()
        {
            if (GetLiftOffState() == LiftOffState.Land)
            {
                Console.WriteLine("배럭을 띄운 후 에 이동 가능합니다.");
            }
            else
            {
                Console.WriteLine("배럭이 이동합니다.");
            }

        }

        //정지
        public void Stop()
        {
            if (GetLiftOffState() == LiftOffState.Land)
            {
                Console.WriteLine("배럭을 띄운 후에 명령이 가능합니다.");
            }
            else
            {
                Console.WriteLine("배럭을 멈춥니다.");
            }
        }

        //유닛생성한다 (유닛의 타입)
        public Unit CreateUnit(UnitType unitType)
        {
            int unitDmg = 0;
            int unitHp = 0;
            switch (unitType)
            {
                case UnitType.Marine:
                    unitDmg = 6;
                    unitHp = 100;
                    break;
                case UnitType.Medic:
                    unitDmg = 0;
                    unitHp = 80;
                    break;
                case UnitType.Firebat:
                    unitDmg = 7;
                    unitHp = 100;
                    break;
                case UnitType.Ghost:
                    unitDmg = 10;
                    unitHp = 120;
                    break;
                default:
                    break;
            }

            Unit unit = new Unit(unitType, unitDmg, unitHp);
            return unit;
        }

        //유닛으로부터 피해를 받을수 있다.
        public void Hit(Unit unit, int damage)
        {
            this.hp = maxHp - damage;
            if (this.hp <= 0)
            {
                this.hp = 0;
                Destruction(this, unit);
            }
            else
            {
                Console.WriteLine($"[{this.name}]이(가) [{unit.GetUnitType()}]에게 {damage}의 피해를 받았습니다.({this.hp}/{this.maxHp})");
            }
        }

        //파괴될수 있다.
        public void Destruction(Barracks barracks , Unit unit)
        {
            Console.WriteLine($"[{this.name}]이(가) [{unit.GetUnitType()}]에게 파괴되었습니다.");
            barracks = null;
        }

        // 배럭 내린다.
        public void Land()
        {
            this.liftOffState = LiftOffState.Land;
            Console.WriteLine("> 배럭을 내립니다.");
        }

        //배럭을 공중에 띄운다..
        public void LiftOff()
        {
            this.liftOffState = LiftOffState.LiftOff;
            Console.WriteLine("> 배럭을 띄웁니다.");
        }

        // 리프트 상태값 호출
        public LiftOffState GetLiftOffState()
        {
            return this.liftOffState;
        }

    }
}

> Academy.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200414
{
    class Academy
    {
        public int id;
        public string name; //이름
        public int maxHp; //체력
        public int hp;

        public Academy()
        {
            Console.WriteLine("아카데미가 생성되었습니다.");
            this.name = "아카데미";
        }

        public void Init(int id, int maxHp)
        {
            this.id = id;
            this.maxHp = maxHp;
            this.hp = this.maxHp;
        }

        //유닛으로부터 피해를 받을수 있다.
        public void Hit(Unit unit, int damage)
        {
            this.hp = maxHp - damage;
            if (this.hp <= 0)
            {
                this.hp = 0;
                Destruction(this, unit);
            }
            else
            {
                Console.WriteLine($"[{this.name}]이(가) [{unit.GetUnitType()}]에게 {damage}의 피해를 받았습니다.({this.hp}/{this.maxHp})");
            }
        }

        //파괴될수 있다.
        public void Destruction(Academy academy, Unit unit)
        {
            Console.WriteLine($"[{this.name}]이(가) [{unit.GetUnitType()}]에게 파괴되었습니다.");
            academy = null;
        }
    }
}

 

> App.cs

더보기
                PlayerPlane playerPlane = new PlayerPlane("비행기", 0, -6);

                Monster monster = new Monster("악당",0, 9, 1);

                Bullet bullet = playerPlane.Shoot(1, monster);

                Console.WriteLine("총알소멸");
                //총알 객체 삭제
                bullet = null;

 

> PlayerPlane.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200413
{
    class PlayerPlane
    {
        public string name;
        public int damage;
        public int x;
        public int y;
        public Bullet bullet;

        public PlayerPlane() { }

        public PlayerPlane(string name, int x, int y) {
            this.name = name;
            this.x = x;
            this.y = y;
            Console.WriteLine($"{this.name}이 생성되었습니다.({this.x}/{this.y})");
        }
        
        public Bullet Shoot( int damage, Monster monster) {
            bullet = new Bullet(this.x, this.y, damage);
            bullet.Move(monster);
            return bullet; 
        }
    }
}

 

> Bullet.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200413
{
    class Bullet
    {
        public string name;
        public int damage;
        public int x;
        public int y; 

        public Bullet() { }

        public Bullet(int x, int y, int damage) {
            this.damage = damage;
            this.x = x;
            this.y = y;
            Console.WriteLine($"총알이 생성되었습니다.[damage: {this.damage} ({this.x}/{this.y})]");
        }

        public string Move(Monster monster)
        {
            string check = "";
            
            for (int i = this.y; i <= 10; i++)
            {
                Console.WriteLine($"총알위치: ({this.x}/{i})");
                if (this.x == monster.x && i == monster.y)
                {
                    Console.WriteLine($"몬스터 격추 ({this.x}/{i})");
                    check = "격추";
                    break;
                }
                check = "통과";
            }
            return check;
        }
    }
}

 


> App.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200413
{
    class App
    {
        public App()
        {
            Factory factory = new Factory();
            SiegeTank siegeTank = factory.CreateSiegeTank();
            siegeTank.CreateTank();
            siegeTank.Move();
            siegeTank.SiegeMode();
            siegeTank.Move();
            siegeTank.UnSiegeMode();
            siegeTank.Move();
        }
    }
}

 

> SiegeTank.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200413
{
    enum eAttactMode { TankMode, SizeMode }

    class SiegeTank
    {
        eAttactMode attactMode;

        public SiegeTank()
        {
            this.attactMode = eAttactMode.TankMode;
        }

        public SiegeTank CreateTank()
        {
            SiegeTank siegeTank = new SiegeTank();
            Console.WriteLine("시즈탱크 생성");

            return siegeTank;
        }

        public void SiegeMode()
        {
            this.attactMode = eAttactMode.SizeMode;
            Console.WriteLine("시즈모드로 변경했습니다.");
        }

        public void UnSiegeMode()
        {
            this.attactMode = eAttactMode.TankMode;
            Console.WriteLine("탱크모드로 변경했습니다.");
        }

        public void Move()
        {
            if (this.attactMode != eAttactMode.SizeMode)
            {
                Console.WriteLine("시즈탱크가 이동합니다.");
            }
            else
            {
                Console.WriteLine($"{this.attactMode}에서는 이동할수 없습니다.");
            }
        }
    }
}

 


> 강사님코드 - 모드변경 한곳에서 처리

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study_008
{
    class Factory
    {
        //생성자 
        public Factory()
        {
            Console.WriteLine("팩토리가 생성되었습니다.");
        }

        //시즈탱크 생성 
        public SiegeTank CreateSiegeTank()
        {
            return new SiegeTank();
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study_008
{
    public enum eAttackMode
    {
        TankMode, SiegeMode
    }

    class SiegeTank
    {
        public eAttackMode attackMode;

        //생성자 
        public SiegeTank()
        {
            Console.WriteLine("시즈탱크가 생성되었습니다.");
            this.attackMode = eAttackMode.TankMode;
        }

        //이동 
        public void Move()
        {
            if (this.attackMode == eAttackMode.TankMode)
            {
                Console.WriteLine("이동 합니다.");
            }
            else if ( this.attackMode == eAttackMode.SiegeMode) 
            {
                Console.WriteLine("{0}에서는 이동 할수 없습니다.", this.attackMode);
            }
        }

        //모드 변환 
        public eAttackMode ChangeAttackMode()
        {
            eAttackMode prevMode = this.attackMode;

            if (this.attackMode == eAttackMode.SiegeMode)
            {
                this.attackMode = eAttackMode.TankMode;
            }
            else 
            {
                this.attackMode = eAttackMode.SiegeMode;
            }
            Console.WriteLine("{0} -> {1}", prevMode, this.attackMode);

            return this.attackMode;
        }
    }
}

> 캐릭터 정보확인

 

> 아이템 생성

 

> 무기착용

 

> 무기해제

 

 

> 공격

 

> 캐릭터 사망

 


> Item.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200410_2
{
    class Item
    {
        public string name;
        public int damage;


        public Item() { }

        // 아이템 생성
        public Item (string getItemName, int getItemDamage)
        {
            this.name = getItemName;
            this.damage = getItemDamage;
            Console.WriteLine($" [{this.name}]이(가) 생성되었습니다.(Dmage: {this.damage})]");
        }
    }
}

 

> Character.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200410_2
{
    class Character
    {
        public string name;
        public int maxHp;
        public int hp;
        public int damage;
        public Item item;
        public bool checkedEquip;

        public Character() { }


        public Character(string name, int maxHp, int damage) {
            this.name = name;
            this.maxHp = maxHp;
            this.hp = this.maxHp;
            this.damage = damage;
        }

        public void ShowCharacter()
        {
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            Console.WriteLine($"▶ 캐릭터 이름: {this.name}\n( { hp } / { maxHp } )\n공격력: { (this.item != null ? this.item.damage+this.damage : this.damage) }");
            Console.Write("▶ 착용 무기:");
            if(this.item !=null){
                Console.WriteLine($"{this.item.name}");
            }else{
                Console.WriteLine($" 없음");
            }
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
        }

        public void ViewItem()
        {
            Console.WriteLine($"무기: {this.item.name}\n데미지: {this.item.damage}");
        }

        // 아이템 착용
        public void EquipItem(Item item){
            if(checkedEquip){
                Console.WriteLine("이미 착용 중 입니다.");
            }else{
                this.item = item;
                checkedEquip = true;
                Console.WriteLine($"{this.item.name}을(를) 착용 하였습니다.");
            }
        }


        // 아이템 해제
        public void UnEquipItem(Item Item){
            if(checkedEquip){
                Console.WriteLine($"{this.item.name}을(를) 해제 하였습니다.");
                this.item = null;
                checkedEquip = false;
            }else{
                Console.WriteLine("착용중인 아이템이 없습니다.");
            }
        }


        // 공격
        public void Attack(Character target){
           // Console.WriteLine($"target: {target.name} / this.: {this.name}");

            int fullDamage = this.damage;
        
         if(this.item != null && this.checkedEquip){
            fullDamage = this.damage + this.item.damage;
            Console.WriteLine($"[{this.name}]이(가) [{target.name}]을(를) [{this.item.name}]으로 공격했습니다.");
         }else{
            Console.WriteLine($"[{this.name}]이(가) [{target.name}]을(를) [맨손]으로 공격했습니다.");
         }  
            target.Hit(this, fullDamage);
        }

        // 피해
        public void Hit(Character target, int damage){
            //Console.WriteLine($"target: {target.name} / this.: {this.name}");

            // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ 용자 -> 마왕
            this.hp -= damage;

            if(this.hp <= 0){
                this.hp = 0;
            }

            Console.WriteLine($"{target.name}는 {this.name}에게 {damage}의 피해를 주었습니다. [{this.name}:({this.hp}/{this.maxHp})]");
            Console.WriteLine();
            
            if(this.hp <= 0){
                Die();
                return;
            }

            // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ 마왕 -> 용자

            target.hp -= this.damage;

            if(target.hp <= 0){
                target.hp = 0;
            }

            Console.WriteLine($"{this.name}에게 {this.damage}의 피해를 받았습니다. [{target.name}:({target.hp}/{target.maxHp})]");
            Console.WriteLine();
            
            if(target.hp <= 0){
                target.Die();
                GameOver();
                return;
            }
        }

        // 죽을 수 있다.
        public void Die(){
        Console.WriteLine($"{this.name}이(가) 사망했습니다.");
        }

        // 게임 종료 - 재시작
        public void GameOver(){
            Console.WriteLine($"♬ GameOver ♬");
            Console.Write($"게임 재시작 - 1번 입력: ");
            var gameOver = Console.ReadLine();
        
            if(gameOver == "1"){
                Console.Clear();
                new App();
            }    
        }

    }
}

 

> App.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200410_2
{
    class App
    {
        Character hero;
        Character monster;
        Item newItem;

        Item item;

        public App()
        {
           // 캐릭터 생성
            hero  = new Character("용자", 80 , 10);
            monster  = new Character("마왕", 100 , 20);
       
            while(true){
            Console.WriteLine();
                Console.WriteLine(" [1.공격] [2.아이템 제작] [3.무기착용] [4.무기해제] [5.캐릭터 정보확인]");
                Console.Write(" 번호입력: ");
                string inputNum = Console.ReadLine();
                playView(inputNum);
            }
            Console.WriteLine();
        }


        public void playView(string inputNum){
            switch (inputNum)
	        {
		        case "1": //공격
                {
                    hero.Attack(monster);
                    break;
                }
                case "2": //아이템제작
                {
                   Console.Write("아이템 이름: ");
                   string createItemName = Console.ReadLine();     
                   Console.Write("아이템 공격력: ");
                   int createItemDamage = int.Parse(Console.ReadLine());     

                   newItem = new Item(createItemName, createItemDamage);

                   break;
                }
                case "3": // 아이템 착용
                {
                    if(newItem != null)
                    {
                        hero.EquipItem(newItem);
                    }else{
                        Console.WriteLine("착용할 아이템이 없습니다.");
                    }
                    break;
                }
                case "4": // 아이템 해제
                {
                    if(newItem != null)
                    {
                        hero.UnEquipItem(newItem);
                    }else{
                        Console.WriteLine("해제할 아이템이 없습니다.");
                    }
                    break;
                }
                case "5":  // 캐릭터 정보 확인
                {
                    hero.ShowCharacter();
                    break;
                }
                default:
                    Console.WriteLine("번호를 다시 입력해주새요");
                    break;
	        }
        }
    }
}

 

> 나중에 분명히 잊고 찾을 것 같아 기록해둔다. 

        public App()
        {
            int result = (int)Enum.Parse(typeof(Days), "Friday");
            Console.WriteLine(result);

            var result2 = Enum.Parse(typeof(Days), "Friday");
            Console.WriteLine(result2);
            Console.WriteLine(result2.ToString());

        }

 

 

 enum Days { Monday, Tuesday, Wedneday, Thursday, Friday, Saturday, Sunday }

> Enum.GetValues() 받는 타입을 int 줄경우 인덱스를 출력 할 수 있다. 

            foreach (int r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine(r);
            }

 

> Enum 타입이나, var 타입으로 받아 출력 할 수 있다.

            foreach (Days r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine(r);
            }

 

 


 

> GetNames() , GetValues() 둘다 콘솔에 리스트 문자열은 같으나,  확인해보니 리턴 받는 타입이 다르다.

 


 

> Enum의 Length (Get.Names() 도 Length 확인가능)

            foreach (var r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine( Enum.GetValues( typeof(Days) ).Length );
            }

 

        public void weaponPlus()
        {
            int swordPlus = 0;
            int axePlus = 0;

            while (true)
            {
                Console.WriteLine("> 소지중인 아이템: Sword, Axe");
                Console.Write("-강화하시려는 무기의 이름을 입력해주세요: ");
                WeaponType inputWeapon = (WeaponType)Enum.Parse(typeof(WeaponType), Console.ReadLine());
                Console.WriteLine("> 강화확률 Sword:30%, Bow:25%, Axe:20%");
                Console.Write("-강화하시려면 '강화'를  입력해주세요: ");

                Console.WriteLine();

                Random rd = new Random();

                var p = rd.Next(1, 100);

                switch (inputWeapon)
                {
                    case WeaponType.Sword:
                        Console.WriteLine("random: " + p);

                        if (p <= 30)
                        {
                            swordPlus++;
                            Console.WriteLine($"아이템( { inputWeapon }) 강화에 성공했습니다.");
                            Console.WriteLine($"소지중인 아이템 : { inputWeapon }(+{swordPlus}), Axe");
                        }
                        else
                        {
                            Console.WriteLine("강화실패");
                        }
                        break;
                    case WeaponType.Axe:
                        Console.WriteLine("random: " + p);
                        if (p <= 100)
                        {
                            axePlus++;
                            Console.WriteLine($" { inputWeapon } 강화에 성공했습니다.");
                            Console.WriteLine($"소지중인 아이템 : { inputWeapon }(+{axePlus}), Axe");
                        }
                        else
                        {
                            Console.WriteLine("강화실패");
                        }
                        break;
                    default:
                        Console.WriteLine($"{inputWeapon} 은 없는 아이템입니다.");
                        break;
                }
                Console.WriteLine();
            }
        } //end

Enum 활용 연습 과제지만, 실무에서 이렇게 형 변환하여 사용하는 건지 감이 안온다.

'c# 강의 > 과제' 카테고리의 다른 글

20200413 - 팩토리 시즈모드  (0) 2020.04.13
20200410 - 주말 과제  (0) 2020.04.12
20200409 - while,switch(장비 착용,해제,습득,삭제 등 분기처리)  (0) 2020.04.09
20200408 - Enum 과제  (0) 2020.04.08
20200408 - 반복문  (0) 2020.04.08
        public void weaponHave()
        {
            bool itemEqip = true; //장비여부
            string itemName = "장검";

            while (true)
            {
                Console.WriteLine($"소지중인 아이템: { itemName }");
                Console.WriteLine("아이템명 '착용' / 아이템명 '해제' / 아이템명 '집어' / 아이템명 '버려'");
                Console.Write("명령어를 입력 해주세요: ");
                var inputMsg = Console.ReadLine();

                var inputMsgArr = inputMsg.Split(' ');

                switch (inputMsgArr[0])
                {
                    case "장검":
                        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 착용 ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                        if (inputMsgArr[1] == "착용")
                        {
                            if (itemEqip && itemName != null)
                            {
                                Console.WriteLine("이미 착용 되었습니다.");
                            }
                            else if (itemName == null)
                            {
                                Console.WriteLine("장검을 가지고 있지않습니다.");
                            }
                            else
                            {
                                itemEqip = true;
                                Console.WriteLine($"{inputMsgArr[0]}을 착용했습니다.");
                            }
                        }

                        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 해제 ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                        if (inputMsgArr[1] == "해제")
                        {
                            if (itemEqip && itemName != null)
                            {
                                itemEqip = false;
                                Console.WriteLine("해제 했습니다.");
                            }
                            else if (itemName == null)
                            {
                                Console.WriteLine("장검을 가지고 있지않습니다.");
                            }
                            else
                            {
                                Console.WriteLine("해제 할 수 없습니다.");
                            }
                        }

                        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 버려 ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                        if (inputMsgArr[1] == "버려")
                        {
                            if (itemName != null)
                            {
                                if (itemEqip)
                                {
                                    Console.WriteLine("착용된 아이템은 버릴수 없음");
                                }
                                else
                                {
                                   // itemEqip = false;
                                    itemName = null;
                                    Console.WriteLine("장검을 버렸습니다.");
                                }
                            }
                            else
                            {
                                Console.WriteLine("장검을 가지고 있지않습니다.");
                            }
                        }

                        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 집어 ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                        if (inputMsgArr[1] == "집어")
                        {
                            if (itemName == "장검")
                            {
                                Console.WriteLine("이미 장검을 소지하고 있음");
                            }
                            else
                            {
                                itemName = "장검";
                                Console.WriteLine("장검을 획득하였습니다");
                            }
                        }
                        break;
                    default:
                        break;
                }
                Console.WriteLine();
            }
        }

'c# 강의 > 과제' 카테고리의 다른 글

20200410 - 주말 과제  (0) 2020.04.12
20200409 - Enum 활용(강화 기능)  (0) 2020.04.10
20200408 - Enum 과제  (0) 2020.04.08
20200408 - 반복문  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07

 

 

 

        enum RaceType { Human, Elf, Ork } // 종족
        enum Human { Warrior, Rogue }
        enum Elf { Mage, Hunter }
        enum Ork { Monk, Rogue }

 

        public void enumWow()
        {
            Console.WriteLine("======================== WoW ========================");
            int index1 = 1;
            
            foreach (RaceType r in Enum.GetValues(typeof(RaceType)))
            {
                Console.Write($"[{index1++}. {r}] ");
            }
            Console.WriteLine();
            Console.WriteLine("=====================================================");
            while (true)
            {
                Console.Write("종족 선택: ");
                var raceInput = (RaceType)(int.Parse(Console.ReadLine()) - 1);
                int index2 = 1;
                switch (raceInput)
                {
                    case RaceType.Human:
                        {
                            Console.WriteLine($"{raceInput} 을 선택하셨습니다.");
                            foreach (Human h in Enum.GetValues(typeof(Human)))
                            {
                                Console.Write($"[{index2++}.{h}] ");
                            }
                            Console.Write("직업을 선택해주세요: ");
                            var classInput = (Human)(int.Parse(Console.ReadLine()) - 1);
                            Console.WriteLine($"{ (Human)classInput } 을 선택하셨습니다.");
                            break;
                        }
                    case RaceType.Elf:
                        {
                            Console.WriteLine($"{raceInput} 을 선택하셨습니다.");
                            foreach (Elf e in Enum.GetValues(typeof(Elf)))
                            {
                                Console.Write($"[{index2++}.{e}] ");
                            }
                            Console.Write("직업을 선택해주세요: ");
                            var classInput = (Elf)(int.Parse(Console.ReadLine()) - 1);
                            Console.WriteLine($"{ (Elf)classInput } 을 선택하셨습니다.");
                            break;
                        }
                    case RaceType.Ork:
                        { 
                        Console.WriteLine($"{raceInput} 을 선택하셨습니다.");
                            foreach (Ork o in Enum.GetValues(typeof(Ork)))
                            {
                                Console.Write($"[{index2++}. {o}] ");
                            }
                            Console.Write("직업을 선택해주세요: ");
                            var classInput = (Ork)(int.Parse(Console.ReadLine()) - 1);
                            Console.WriteLine($"{ (Ork)classInput } 을 선택하셨습니다.");
                            break;
                        }
                    default:
                        Console.WriteLine("번호를 정확하게 입력해주세요");
                        break;
                }// switch end
                Console.WriteLine();
            } //while end
        }

> 선언 및 리스트 출력

enum days
{
	Monday, Tuesday, Wedneday, Thursday, Friday, Saturday, Sunday
}

public void enumTest()
{
	foreach (days i in Enum.GetValues(typeof(days)))
	{
		Console.WriteLine(i);
	}
}

 


 

> 형변환(int) switch  활용

    	public void enumTest()
        {
            Console.WriteLine("( 0: sword, 1: bow, 2: axe )");
            Console.Write("아이템 번호 입력: ");
            var inputNum = int.Parse(Console.ReadLine());

            switch (inputNum)
            {
                case (int)Weapons.Sword:
                    Console.WriteLine($"{Weapons.Sword} 를 착용");
                    break;
                case (int)Weapons.Bow:
                    Console.WriteLine($"{Weapons.Bow} 를 착용");
                    break;
                case (int)Weapons.Axe:
                    Console.WriteLine($"{Weapons.Axe} 를 착용");
                    break;
                default:
                    Console.WriteLine("입력 번호 오류");
                    break;
            }
        }

 


> 형변환(enum선언타입) - 입력받은 string데이터로 활용(문자열 출력시 .toToString()) 

        enum Weapons { Sword, Bow, Axe }
        public void enumCheang()
        {
            Console.Write("아이템 입력: ");
            var input = Console.ReadLine();
            Weapons getName = (Weapons)Enum.Parse(typeof(Weapons), input);
            Console.WriteLine($"{ getName }를 착용했습니다.");
        }

Action

 Console.WriteLine("[ '장검', '단검', '활', '도끼' ]");
 Console.Write("구매하고자 하는 아이템 이름 입력: ");
 
 var checkInput = Console.ReadLine();
 
   // 함수내부에 action 선언 return이 없음 - void형
   // 제네릭 명시 필요 
   Action<string> msg = (inputMsg) =>
   {
   		Console.WriteLine($"{inputMsg}를 구매하셨습니다.");
   };
switch (checkInput)
                {
                    case "장검":
                        msg(checkInput);
                        break;

 

 

Func

  // 함수내부에 Func 제네릭<인자,리턴타입> 후 화살표 함수 사용 후 return  
  Func<string, string> msgFunc = (inputMsg) =>
  	{
    	return $"{inputMsg}를 구매하셨습니다.";
    };
 switch (checkInput)
 	{
    	case "단검":
        	var str = msgFunc(checkInput);
        	Console.WriteLine(str);
        	break;

가상 캐릭터 이동 및 획득

 

    public void scvMovingTest()
        {
            int x = 0;
            int y = 0;

            int itemX = 3;
            int itemY = 0;

            bool itemChecked = true;

            Console.WriteLine("유닛명: SCV");
            Console.WriteLine("L: 횟수 / R: 횟수 --- 최대3");
            Console.WriteLine("U: 횟수 / D: 횟수 --- 최대3");

            Console.WriteLine("유닛의 초기 위치: (0,0)");

            while (true)
            {
                Console.Write("유닛을 이동하려면 명령어를 입력하세요 : ");
                var input = Console.ReadLine();
                var inputArr = input.Split(' ');

                Console.WriteLine($"--현재위치: ({x}, {y})");
                Console.WriteLine();

                int parseInputArr = int.Parse(inputArr[1]);

                for (int i = 1; i < (parseInputArr + 1); i++)
                {
                    // 최대 3칸 이동
                    if (i > 3) break;

                    // ㅡㅡㅡㅡㅡㅡㅡㅡ left ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                    if (inputArr[0] == "l")
                    {
                        Console.Write("◁ -- left : ");
                        x++;
                        Console.WriteLine($"({x},{y})");
                    }

                    // ㅡㅡㅡㅡㅡㅡㅡㅡ right ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                    if (inputArr[0] == "r")
                    {
                        Console.Write("▶ -- right : ");
                        x--;
                        Console.WriteLine($"({x},{y})");
                    }

                    // ㅡㅡㅡㅡㅡㅡㅡㅡ up ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                    if (inputArr[0] == "u")
                    {
                        Console.Write("▲up -- : ");
                        y++;
                        Console.WriteLine($"({x},{y})");
                    }

                    // ㅡㅡㅡㅡㅡㅡㅡㅡ down ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
                    if (inputArr[0] == "d")
                    {
                        Console.Write("▼down -- : ");
                        y--;
                        Console.WriteLine($"({x},{y})");
                    }

                    // ㅡㅡㅡㅡㅡㅡㅡㅡㅡ item ㅡㅡㅡㅡㅡㅡㅡㅡ
                    if (x == itemX && y == itemY)
                    {
                        if (!itemChecked)
                        {
                            Console.WriteLine("빈 상자 발견");
                        }
                        else
                        {
                            Console.WriteLine("장검 획득!!");
                            itemChecked = false;
                        }
                    }
                }
            }
        }// scv end

 


 

 

 

 

public void knight()
        {
            Console.Write("캐릭터 이름: ");
            var heroName = Console.ReadLine();

            Console.Write("애니메이션[1] 이름: ");
            var aniName1 = Console.ReadLine();
            Console.Write("애니메이션[1] 총 프레임: ");
            var aniFream1 = int.Parse(Console.ReadLine());


            Console.Write("애니메이션[1] 이름: ");
            var aniName2 = Console.ReadLine();
            Console.Write("애니메이션[1] 총 프레임: ");
            var aniFream2 = int.Parse(Console.ReadLine());

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
            while (true)
            {
                Console.Write("애니메이션을 실행하시려면 애니메이션 이름을 입력하세요: ");
                var input = Console.ReadLine();

                // 애니 실행

                if (input == aniName1)
                {
                    for (int i = 1; i <= aniFream1; i++)
                    {
                        Console.WriteLine($"{heroName}_{aniName1}_00{i}");
                    }

                    Console.WriteLine($"{heroName}_{aniName1} ani complate.");
                    Console.WriteLine();
                }
                else if (input == aniName2)
                {
                    for (int i = 1; i <= aniFream2; i++)
                    {
                        Console.WriteLine($"{heroName}_{aniName2}_00{i}");
                    }
                    Console.WriteLine($"{heroName}_{aniName2} ani complate.");
                    Console.WriteLine();
                    for (int i = 1; i <= aniFream1; i++)
                    {
                        Console.WriteLine($"{heroName}_{aniName1}_00{i}");
                    }

                    Console.WriteLine($"{heroName}_{aniName1} ani complate.");
                }
            }
        }// knight

'c# 강의 > 과제' 카테고리의 다른 글

20200409 - while,switch(장비 착용,해제,습득,삭제 등 분기처리)  (0) 2020.04.09
20200408 - Enum 과제  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07
20200407 - 장검 과제  (0) 2020.04.07
20200406 - for문 별찍기  (0) 2020.04.06

 

 public void idle2()
        {
            Console.Write("실행할 애니메이션의 이름을 적으세요: ");
            var aniName = Console.ReadLine();

            Console.Write("애니메이션의 total 프레임은 몇 프레임 입니까? : ");
            var totalFream = int.Parse(Console.ReadLine());

            Console.Write("애니메이션의 타격 프레임은 몇 프레임 입니까? : ");
            var effectFream = int.Parse(Console.ReadLine());

            Console.Write("애니메이션의 타격 프레임때 쓸 에픽트 효과는? : ");
            var effectMsg = Console.ReadLine();

            Console.Write("에이메이션을 실행하려면 play 입력하세요: ");
            var playMsg = Console.ReadLine();

            int num = 1;

            if (playMsg == "play")
            {
                while (true)
                {
                    if (num <= totalFream)
                    {
                        Console.WriteLine($"{aniName} {num}을 프레임을 실행");
                        num++;

                        if (num == effectFream)
                        {
                            Console.WriteLine($"{effectMsg}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("애니메이션 종료");
                        break;
                    }
                }//while
            }
        }

 

 

 


 

public void whileTest2()
        {
            int num = 1;
            Console.Write("최대 3개: ");
            var input = Console.ReadLine();

            var arr = input.Split(',');

            Console.WriteLine(arr.Length);

            while (true)
            {
                for (int j = 1; j < 10; j++)
                {
                    for (int i = 0; i < arr.Length; i++)
                    {
                        Console.Write($"{arr[i]} x {j} = { int.Parse(arr[i]) * j }   ");
                    }
                    Console.WriteLine();

                    if (j == 9)
                    {
                        return;
                    }
                }
            }
        }

 

 


 

public void idle3()
        {
            //ㅡㅡㅡㅡㅡㅡㅡㅡ ani1 ㅡㅡㅡㅡㅡㅡㅡㅡ
            Console.Write("공격 애니메이션1: ");
            var aniName1 = Console.ReadLine();

            Console.Write("공격 애니메이션1 의 total: ");
            var totalFream1 = int.Parse(Console.ReadLine());

            Console.Write("공격 애니메이션1 타격 프레임 : ");
            var effectFream1 = int.Parse(Console.ReadLine());

            Console.Write("애니메이션1 의 타격 프레임 에픽트 효과: ");
            var effectMsg1 = Console.ReadLine();

            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");

            //ㅡㅡㅡㅡㅡㅡㅡㅡ ani2 ㅡㅡㅡㅡㅡㅡㅡㅡ
            Console.Write("공격 애니메이션2: ");
            var aniName2 = Console.ReadLine();

            Console.Write("공격 애니메이션2 의 total: ");
            var totalFream2 = int.Parse(Console.ReadLine());

            Console.Write("공격 애니메이션2 타격 프레임 : ");
            var effectFream2 = int.Parse(Console.ReadLine());

            Console.Write("애니메이션2 의 타격 프레임 에픽트 효과: ");
            var effectMsg2 = Console.ReadLine();

            //ㅡㅡㅡㅡㅡㅡㅡㅡ 기본 ㅡㅡㅡㅡㅡㅡㅡㅡ
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
            Console.Write("기본 애니메이션 이름: ");
            var defAniName = Console.ReadLine();
            Console.Write("기본 애니메이션 의 total: ");
            var defAniFream = int.Parse(Console.ReadLine());

            int currentFream = 0;
            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ 1
            while (true)
            {
                if (currentFream >= totalFream1) { 
                    break; 
                }

                currentFream++;
                if (currentFream == effectFream1)
                {
                    Console.WriteLine($"{effectMsg1}");
                }else
                {
                Console.WriteLine($"{aniName1} {currentFream} frame");
                }
            }
            Console.WriteLine();

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ 2
            currentFream = 0;
            while (true)
            {
                if(currentFream >= totalFream2)
                {
                    break;
                }
                currentFream++;
                if(currentFream == effectFream2)
                {
                    Console.WriteLine($"{effectMsg2}");
                    currentFream++;
                }
                Console.WriteLine($"{aniName2} {currentFream} frame");
            }
            Console.WriteLine();

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ de
            currentFream = 0;
            while (true)
            {
                currentFream++;
                Console.WriteLine($"{defAniName} {currentFream} frame");
                if (currentFream >= defAniFream)
                {
                    Console.WriteLine("애니메이션 종료");
                    break;
                }
            }
        }

 

'c# 강의 > 과제' 카테고리의 다른 글

20200408 - Enum 과제  (0) 2020.04.08
20200408 - 반복문  (0) 2020.04.08
20200407 - 장검 과제  (0) 2020.04.07
20200406 - for문 별찍기  (0) 2020.04.06
20200403 - for문 과제 1  (0) 2020.04.03
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200407
{
    class app
    {
        public app()
        {

            heroTest();
        }


        public void heroTest()
        {
            double heroAtt = 0;
            int monsterMaxHp = 0;
            double monsterHp = 0;

            int critical = 0;

            buldColor();

            for (; ; )
            {
                Console.Write(" - 영웅의 공격력은 몇 입니까?(1-5)? : ");
                // 입력  범위 아니면 범위를 벗어 났습니다.

                heroAtt = Convert.ToInt32(Console.ReadLine());

                if (heroAtt > 0 || heroAtt > 6)
                {
                    break;
                }
                else
                {
                    redColor();
                    Console.WriteLine(" ! 범위가 잘못되었습니다.");
                    buldColor();
                }
            }




            for (; ; )
            {
                Console.Write(" - 몬스터의 체력은 몇 입니까?( 10 ~ 20 ) : ");
                monsterMaxHp = Convert.ToInt32(Console.ReadLine());

                if (monsterMaxHp > 9 && monsterMaxHp < 21)
                {
                    monsterHp = monsterMaxHp;

                    break;
                }
                else
                {
                    redColor();
                    Console.WriteLine(" ! 범위가 잘못되었습니다.");
                    buldColor();
                }
            }


            // 공격
            for (; ; )
            {
                Console.Write(" - 공격을 하시려면 '공격'을 입력하세요. : ");
                string checkMsg = Console.ReadLine();
                if (checkMsg == "공격")
                {
                    if (monsterHp > 0)
                    {

                        var rand = new Random();

                        critical = rand.Next(1, 99);
                        // Console.WriteLine($"{critical} ????" );

                        if (critical > 50)
                        {
                            // 크리티컬
                            double criAtt = heroAtt * 1.5;
                            monsterHp = monsterHp - heroAtt;
                            yellowColor();
                            Console.WriteLine(" - ★ 치명타 발생");
                            Console.WriteLine($" - 몬스터를 '세게' 공격 했습니다. -{criAtt} ({monsterHp} / {monsterMaxHp} )");
                            buldColor();
                        }
                        else
                        {
                            // 일반공격
                            monsterHp = monsterHp - heroAtt;
                            Console.WriteLine($" - 몬스터를 공격 했습니다. -{heroAtt} ({monsterHp} / {monsterMaxHp} )");
                        }

                        if (monsterHp <= 0)
                        {
                            yellowColor();
                            Console.WriteLine(" - 몬스터가 쓰러졌습니다. ");
                            buldColor();
                            break;
                        }
                    }
                }
                else
                {
                    redColor();
                    Console.WriteLine(" ! 없는 명령어 입니다. ");
                    buldColor();
                }
            } // 공격 for

            // 아이템 획득
            for (; ; )
            {
                yellowColor();
                Console.WriteLine(" - 몬스터가 아이템(장검) 떨어뜨렸습니다.");
                buldColor();
                Console.Write(" - 아이템 획득하려면 '장검 집어'를 입력 하세요 : ");

                string userMsg = Console.ReadLine();

                // Contains
                // bool result = sysMsg.Contains(userMsg);

                // Replace
                string checkMsg = userMsg.Replace(" ", "");
                bool result1 = checkMsg.Contains("장검");
                bool result2 = checkMsg.Contains("집어");

                // Console.WriteLine($"[ {checkMsg} ]잘라낸거");
                // Console.WriteLine($"result1: {result1} / result2: {result2}");

                if (result1 && result2)
                {
                    whiteColor();
                    Console.WriteLine(" - 장검을 획득했습니다.");
                    buldColor();
                    break;
                }
                else if (!result1)
                {
                    redColor();
                    Console.WriteLine($" ! '장검' 을 정확하게 입력해주세요. ");
                    buldColor();
                }
                else if (!result2)
                {
                    redColor();
                    Console.WriteLine($" ! '집어' 를 정확하게 입력해주세요. ");
                    buldColor();
                }else if (!result1 && !result2)
                {
                    redColor();
                    Console.WriteLine($" ! '장검','집어' 를 정확하게 입력해주세요. ");
                    buldColor();
                }
            } //for
        } // method


        public void buldColor()
        {
            Console.ForegroundColor = ConsoleColor.Blue;
        }

        public void redColor() {
            Console.ForegroundColor = ConsoleColor.Red;
        }

        public void yellowColor()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
        }

        public void whiteColor()
        {
            Console.ForegroundColor = ConsoleColor.White;
        }

    }
}

 

'c# 강의 > 과제' 카테고리의 다른 글

20200408 - 반복문  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07
20200406 - for문 별찍기  (0) 2020.04.06
20200403 - for문 과제 1  (0) 2020.04.03
20200402 - 연산자 과제  (0) 2020.04.02

Replace - 앞 인자를 뒷 인자로 대체 후 리턴

string str = "할머니";

string temp = str.Replace("머",""); // temp = 할니;



 

Contains - 포함하고 있는 문자열 여부

string str = "할머니";
bool result = str.Contains("머"); // true 리턴

 

Split - 문자열 기준 잘라 배열로 리턴

 var input = Console.ReadLine();
 var arr = input.Split(' '); // char 타입 배열로 리턴
          
 int a = int.Parse(arr[0]);
 int b = int.Parse(arr[1]);
// 입력 java로는 - scanner
string input = Console.ReadLine(); 

// 출력
Console.WriteLine("output");

// 콘솔 삭제
Console.Clear();

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Class1
    {
        public Class1()
        {

            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    Console.Write("☆");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

            for (int i = 5; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("☆");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

            for (int i = 5; i > 0; i--)
            {
                for (int j = 5; j >= i; j--)
                {
                    Console.Write("☆");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");

            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 4 - i; j++)
                {
                    Console.Write("  ");
                }


                for (int k = 0; k < i * 2 + 1; k++)
                {
                    Console.Write("☆");

                }
                Console.WriteLine("");
            }
        }
    }
}

 

 

 

 

'c# 강의 > 과제' 카테고리의 다른 글

20200408 - 반복문  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07
20200407 - 장검 과제  (0) 2020.04.07
20200403 - for문 과제 1  (0) 2020.04.03
20200402 - 연산자 과제  (0) 2020.04.02

 

 

 


 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace study_002
{
    class App
    {
        public App()
        {
            string hero = "아이언맨";
            string monster = "타노스";
            double heroMaxHp = 10;
            double heroHp;
            int monsterDmage = 3;
 
            Console.WriteLine($"{hero}의 체력은 {heroMaxHp} 입니다.");
            Console.WriteLine($"{monster}의 공격력은 {monsterDmage} 입니다.");
 
            heroHp = heroMaxHp;
 
            for (int i = 1; i < 5; i++)
            {
                heroHp = heroHp - monsterDmage;
                Console.WriteLine($"{hero}이 {monster}에게 {monsterDmage}의 공격을 받았습니다.");
                Console.WriteLine($"{hero}의 체력은 {heroHp} 입니다.");
                Console.WriteLine();
 
            }
 
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
 
            string newName = "홍길동";
            Console.WriteLine("빵의 갯수는 5개 입니다.");
 
            for (int i = 5; i > -1; i--)
            {
                Console.WriteLine($"{newName}님이 빵을 먹었습니다.");
                Console.WriteLine($"{i}개의 빵이 남았습니다.");
            }
 
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
 
            for (int i=1; i<10; i++)
            {
                Console.WriteLine($"2 x {i}");
            }
 
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
 
            for (int i = 1; i < 10; i++)
            {
                Console.WriteLine($"2 x {i} = {2*i}");
            }
 
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

* 결과

'c# 강의 > 과제' 카테고리의 다른 글

20200408 - 반복문  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07
20200407 - 장검 과제  (0) 2020.04.07
20200406 - for문 별찍기  (0) 2020.04.06
20200402 - 연산자 과제  (0) 2020.04.02

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace unityStudy
{
    class App
    {
 
        float c;
 
        public App() // 생성자
        {
            Console.WriteLine("Helloworld");
 
            // 데이터 형식
 
            // 숫자 (값형식)
            // 정수
            // 부동 소수점
 
            // 문자 
 
            int a = 5;
            Console.WriteLine(a);
 
 
            string name = "조효준";
            Console.WriteLine(name);
 
            float b = 5.4f;
            Console.WriteLine(b);
                
            Console.WriteLine(c);
 
            Console.WriteLine(name + " " + a + " " + b);
 
            string heroName = "\"" + "아이언맨" + "\"";
            Double heroMaxHp = 10;
 
            string monsterName = "\"" + "타노스" + "\"";
            Double monsterDamage = 3;
            Double heroHp = heroMaxHp - monsterDamage;
 
           
 
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
 
            //타노스가 아이언맨을 공격 했습니다.
            Console.WriteLine(monsterName +  "가 " + heroName+ "을 " + monsterDamage + " 만큼 공격 했습니다" );
            Console.WriteLine(heroName + "의 체력은 (" + heroHp + "/" + heroMaxHp + ") 입니다.");
            
            Console.WriteLine(heroName + "의 체력은 (" + heroHp + "/" + heroMaxHp + ")," + (heroHp / heroMaxHp)*100  + "% 입니다.");
 
 
 
 
 
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

쌍따옴표 출력 방법

'c# 강의 > 과제' 카테고리의 다른 글

20200408 - 반복문  (0) 2020.04.08
20200407 - while 과제  (0) 2020.04.07
20200407 - 장검 과제  (0) 2020.04.07
20200406 - for문 별찍기  (0) 2020.04.06
20200403 - for문 과제 1  (0) 2020.04.03

+ Recent posts