스토리지

과제3 본문

Unity/수업과제

과제3

ljw4104 2021. 3. 10. 23:17

1. 메소드에 반환값과 매개변수가 없는 경우

using System;

namespace Study00
{
    class Program
    {
        //클래스 멤버변수
        private static int numSCV = 0;
        private static int numResurrect = 0;
        private static int level = 0;
        static void Main(string[] args)
        {
            CreateSCV();
            Resurrection();
            for (int i = 0; i < 3; i++)
            {
                CreateSCV();
                LevelUp();
            }
            
            CreateHydralisk();
            RebornHydraToLurker();
            BurrowLurker();
            for (int i = 0; i < 3; i++)
            {
                GatherMineral();
            }
            CreateDefiler();
            AttackDarkSwarm();
            CreateUltralisk();
        }

        //SCV 생성
        static void CreateSCV()
        {
            Console.WriteLine("SCV가 생성되었습니다. \tSCV수 : {0}", ++numSCV);
        }

        //부활
        static void Resurrection()
        {
            Console.WriteLine("부활했습니다. \t부활한 횟수 : {0}", ++numResurrect);
        }

        //레벨업
        static void LevelUp()
        {
            Console.WriteLine("레벨업했습니다. \t레벨 : {0}", ++level);
        }

        static void CreateHydralisk()
        {
            Console.WriteLine("히드라가 생겼습니다.");
        }

        static void RebornHydraToLurker()
        {
            Console.WriteLine("히드라가 럴커로 다시 태어났습니다.");
        }

        //럴커가 버로우함
        static void BurrowLurker()
        {
            Console.WriteLine("럴커가 버로우했습니다. 화면 표시 여부 : FALSE");
        }

        static void GatherMineral()
        {
            Console.WriteLine("드론이 미네랄을 채취합니다.");
        }

        static void CreateDefiler()
        {
            Console.WriteLine("디파일러가 생겼습니다.");
        }

        static void AttackDarkSwarm()
        {
            Console.WriteLine("디파일러가 다크스웜을 사용하였습니다.");
        }

        static void CreateUltralisk()
        {
            Console.WriteLine("울트라리스크가 생겼습니다.");
        }
    }
}

변수는 한 블럭에서만 유효하다. 그 블럭이 끝나면 메모리에서 삭제된다. 그러므로 함수가 아닌 클래스의 멤버변수를 static하게 선언하면 다른 함수에서도 동일하게 접근 및 변경할 수 있다.

 

2. 매개변수만 있고 반환값은 없는 경우

using System;

namespace Study00
{
    class Program
    {
        static void Main(string[] args)
        {
            GetItem("노가다 목장갑");
            UsePotion(200);
            AttackBoss(50);
            AttackMagicDamage(20000);
            Move("남", 500);
            CalculateDistance(10, -9);
            verifyTriangle(5, 12, 13);

            Console.WriteLine();
        }

        //아이템 줍기
        static void GetItem(string name)
        {
            Console.WriteLine("{0}을(를) 획득하였습니다.", name);
        }

        //포션 사용
        static void UsePotion(int recoverHp)
        {
            int maxHp = 500;
            int hp = 200;

            Console.WriteLine("포션을 사용하여 {0}만큼 회복하였습니다. ({1}/{2}) {3}%", recoverHp, hp + recoverHp, maxHp, ((float)(hp + recoverHp) / (float)(maxHp) * 100));
        }

        //보스 공격
        static void AttackBoss(int damage)
        {
            int bossHp = 3000;
            Console.WriteLine("보스에게 {0}만큼 데미지가 들어갔습니다. 남은 체력 : {1}", damage, bossHp - damage);
        }

        //보스 마법공격 피격
        static void AttackMagicDamage(int damage)
        {
            int partyHp = 100000;
            int partyNum = 6;

            int leftHp = partyHp - damage * partyNum;
            if (leftHp > 0)
            {
                Console.WriteLine("파티가 생존했습니다.");
            }
            else
            {
                Console.WriteLine("파티가 전멸했습니다.");
            }
        }

        //어느쪽으로 특정 수 만큼 이동
        static void Move(string direct, int dist)
        {
            Console.WriteLine("{0}쪽으로 {1}만큼 이동하였습니다.", direct, dist);
        }

        //특정 좌표에서 2차원 원점까지의 거리계산
        static void CalculateDistance(int xpos, int ypos)
        {
            Console.WriteLine("({0}.{1}) ~ (0.0)까지의 거리 : {2}", xpos, ypos, (int)Math.Sqrt(Math.Pow(xpos, 2) + Math.Pow(ypos, 2)));
        }

        //3변의 길이가 주어졌을때, 직각삼각형인지 확인
        static void verifyTriangle(int a,int b,int c)
        {
            if (c * c == a * a + b * b)
            {
                Console.WriteLine("직각삼각형.");
            }
            else
                Console.WriteLine("직각삼각형 아님.");
        }
    }
}

 

3. 반환값만 있고 매개변수는 없는 경우

using System;

namespace Study00
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CatchCow() + "을(를) 먹었다.");
            Console.WriteLine("적의 체력 : {0}", getEnemyHp());
            Console.WriteLine("소유 자본 : {0}", getCapital());
            Console.WriteLine("무기의 공격력 : {0}", getWeaponAttack());
            Console.WriteLine("커맨드센터의 체력 : {0}", getCommandHp());
            Console.WriteLine("빚 : {0}", GetBorrowedMoney());
            Console.WriteLine("사람 수 : {0}", NumOfPeopleInBuilding());
            Console.WriteLine("죽었나? : {0}", IsDie());
            Console.WriteLine("부활이 가능한가? : {0}", IsResurrectAvailable());
            Console.WriteLine("지금 부화가능한 라바 갯수 : {0}", UsableLarva());
        }

        //소를 잡다
        static private string CatchCow()
        {
            return "소고기";
        }

        //적의 체력을 가져오다.
        static private int getEnemyHp()
        {
            int hp = 100;
            return hp;
        }

        //소유자본을 확인하다
        static private int getCapital()
        {
            int capital = 500000;
            return capital;
        }

        //무기의 공격력을 확인한다.
        static private int getWeaponAttack()
        {
            int weaponAttack = 50;
            return weaponAttack;
        }

        //커맨드센터의 체력을 확인한다.
        static private int getCommandHp()
        {
            int commandHp = 1500;
            return commandHp;
        }

        //돈을 빌리다
        static private int GetBorrowedMoney()
        {
            int dept = 80000;
            return dept;
        }

        //건물안에 있는 사람 수를 확인한다.
        static private int NumOfPeopleInBuilding()
        {
            int peopleInBuilding = 50;
            return peopleInBuilding;
        }

        //죽었는지 살았는지
        static private bool IsDie()
        {
            int hp = 0;
            return hp <= 0 ? true : false;
        }

        //부활이 가능한가?
        static private bool IsResurrectAvailable()
        {
            int resurrectionCount = 0;
            return resurrectionCount > 0 ? true : false;
        }

        //지금 사용가능한 라바의 갯수를 반환
        static private int UsableLarva()
        {
            int larvaCount = 3;
            return larvaCount == 3 ? larvaCount : 0;
        }
    }
}

 

 

4. 메소드에 반환값과 매개변수가 둘 다 존재하는 경우

using System;

namespace Study00
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("1000000원 배팅 : {0}", Gamble(1000000));
            Console.WriteLine("나뭇가지 5개 합성 : {0}", MakeFishingRod("나뭇가지", 5));
            Console.WriteLine("물과 바람 스킬 상성 비교 : 기본공격력의 {0}배", CalculateSkillSynastry("물", "전기"));
            Console.WriteLine("가구제작(재료:나뭇가지) : {0}", MakeFurniture("나뭇가지", 10));
            Console.WriteLine("마법가루를 이용한 엘릭서 합성 성공여부 : {0}", SynthesizePotion("파워엘릭서", "보랏빛 마법가루"));

            string tmp = "";
            tmp += GetChildBloodType('A', 'B');
            if (tmp[0] == 'C')
            {
                tmp = "AB";
            }
            Console.WriteLine("A형과 B형의 자식은? : {0}형", tmp);
            Console.WriteLine("감염력이 3인 코로나바이러스가 10억명한테 퍼지는 턴 : {0}턴", CaculateDisease(3, 1000000000));
            Console.WriteLine("두 무기(500,600)의 강화 결과 : {0}", ReinforceWeapon(500, 600));
            Console.WriteLine("한정가챠를 뽑을 수 있나? : {0}", GetLimitedGacha(3500));
            Console.WriteLine("딜러 VS 나 : {0}", Gambling2(50000));

            Console.WriteLine();
        }

        //도박(확률 0.7%, 배팅비율 : 300배)
        static private int Gamble(int money)
        {
            int betting = (int)(money * 30);
            money -= betting;

            Random r = new Random();
            int prob = r.Next(1, 1001);
            if (prob <= 7)
            {
                betting *= 300;
                money += betting;
            }
            return money > 0 ? money : 0;
        }

        //낚싯대 제작
        static private string MakeFishingRod(string item, int itemNum)
        {
            if (item == "나뭇가지" && itemNum >= 5)
            {
                return "엉성한 낚싯대 1개";
            }
            else if (item == "엉성한 낚싯대" && itemNum >= 3)
            {
                return "낚싯대 1개";
            }

            return "낚싯대 만들기 실패";
        }

        //스킬 상성계산
        static private float CalculateSkillSynastry(string skill1, string skill2)
        {
            float defaultDamage = 1f;
            if (skill1 == "불" && skill2 == "물")
            {
                defaultDamage /= 2;
            }
            else if (skill1 == "물" && skill2 == "전기")
            {
                defaultDamage *= 3;
            }
            else if (skill1 == "불" && skill2 == "바람")
            {
                defaultDamage *= 2;
            }
            else if (skill1 == "언데드" && skill2 == "성")
            {
                defaultDamage = 0;
            }

            return defaultDamage;
        }

        //가구 생성
        static private string MakeFurniture(string item, int num)
        {
            string furniture = String.Empty;
            if (item == "나뭇가지")
            {
                if (num == 3)
                {
                    furniture = "모닥불";
                }
                else if (num == 10)
                {
                    furniture = "빨랫줄";
                }
            }
            else if (item == "목재")
            {
                if (num == 4)
                {
                    furniture = "목제 스툴";
                }
                else if (num == 6)
                {
                    furniture = "목제 체어";
                }
                else if (num == 10)
                {
                    furniture = "목제 낮은 테이블";
                }
            }
            else
                furniture = "제작불가";

            return furniture;
        }

        //물약 합성 (성공확률 50%)
        static private string SynthesizePotion(string potionName1, string material)
        {
            Random r = new Random();
            string newPotionName = String.Empty;
            int successRate = r.Next(1, 101);

            if (successRate > 50)
            {
                newPotionName = material + "로 만들어진 상당한 " + potionName1;
            }
            else
            {
                newPotionName = "물약 합성의 흔적";
            }

            return newPotionName;
        }

        //자식의 혈액형(AO, BO는 생각안함, AB형은 C라고 적음)
        static private char GetChildBloodType(char dadBlood, char momBlood)
        {
            char childBlood = '\0';
            if (dadBlood == 'O' && momBlood == 'O')
            {
                childBlood = 'O';
            }
            else
            {
                if (dadBlood == 'A')
                {
                    if (momBlood == 'A')
                    {
                        childBlood = 'A';
                    }
                    else if (momBlood == 'B')
                    {
                        childBlood = 'C';
                    }
                    else
                    {
                        childBlood = 'A';
                    }
                }
                else if (dadBlood == 'B')
                {
                    if (momBlood == 'A')
                    {
                        childBlood = 'C';
                    }
                    else if (momBlood == 'B')
                    {
                        childBlood = 'B';
                    }
                    else
                    {
                        childBlood = 'B';
                    }
                }
                else
                {
                    if (momBlood == 'A')
                    {
                        childBlood = 'A';
                    }
                    else if (momBlood == 'B')
                    {
                        childBlood = 'B';
                    }
                    else
                    {
                        childBlood = 'O';
                    }
                }
            }

            return childBlood;
        }

        //감염력이 N인 전염병이 X명에게 퍼지는 턴 계산
        static private int CaculateDisease(int n, int x)
        {
            int time = 0;
            int carrier = 0;

            carrier++;
            time++;

            while (carrier < x)
            {
                carrier *= (int)Math.Pow(2, n);
                time++;
            }

            return time;
        }

        //무기강화 (n의 공격력을 가진 무기 + m의 공격력을 가진 무기, 강화 확률은 30%)
        static private int ReinforceWeapon(int n, int m)
        {
            int sumOfAttack = 0;

            Random r = new Random();
            int prob = r.Next(1, 101);
            if (prob <= 30)
            {
                sumOfAttack = n + m;
            }

            return sumOfAttack;
        }

        //가챠
        static private bool GetLimitedGacha(int money)
        {
            float gauge = 0.0f;
            bool isGetAvailableCard = false;
            Random r = new Random();
            while (!isGetAvailableCard || money > 2500)
            {
                if (money < 2500)
                {
                    Console.WriteLine("잔액부족");
                    return isGetAvailableCard;
                }

                int prob = r.Next(1, 1001);
                if (prob <= 3 || gauge == 100f) //확률을 뚫었거나 천장
                {
                    isGetAvailableCard = true;
                }
                gauge += 2.5f;
                money -= 2500;
            }
            return isGetAvailableCard;
        }

        //도박 2 (딜러와 내가 카드를 가지고 함, 높은쪽이 이김)
        static string Gambling2(int money)
        {
            string result = String.Empty;
            Random r = new Random();

            int dealer = (int)(r.Next(1, 13) * 1.15);
            int jerk = r.Next(1, 13);

            if(dealer > jerk)
            {
                return money + ", 이 돈은 딜러것이 되었습니다.";
            }
            else
            {
                return "축하합니다.";
            }
        }
    }
}

'Unity > 수업과제' 카테고리의 다른 글

과제 6  (0) 2021.03.16
과제 5  (0) 2021.03.14
과제 4  (0) 2021.03.12
과제 2  (0) 2021.03.09
과제 1  (0) 2021.03.09
Comments