대리자 콜백 부분이랑 / 이펙트가 에니메이션이 아니고 파티클 시스템이라 시간 많이 잡아 먹음 ㅜㅜ

시간 관계상 누르면 도끼 생성해서 던지는것으로 대체 

> 후기

- winfrom 을 스터디 하고 싶었던 차에 2048을 winfrom으로 만들어보기로 했다.

- 역시 마쏘는 어마어마한 형들이다.  사용하기 쉽게? 만든느낌을 받으며 적용시킬수 있었다.

- 아카데미시절 눈물나게했던,  JAVA Swing.. 요놈으로 게임만들어본 경험이 큰도움이 됬다.

- 아무래도 수학적인 머리가 부족해서, 2차원배열 정렬하는데, 애좀 먹었다. ㄷㄷ 

- 특히 좌우 정렬 공간지각능력 부족인가 ㅜㅜ

- 자바스크립트의 forEach 관련 메소드들이 있엇다면 좀더 쉽게 했을텐데, 머리가 나쁘면 몸이 고생하는것 을 다시 느꼈다.

- 스코어 누적은 잘되는지, 2048만들어서 클리어 해봐야하는데 검증 할 기력이 없다. ㄷㄷ

- 개똥같읕 코드로 반복문과 분기문이 아주 지저분한데, 가볍게 잘돌아가는것 같아 신기했다. 

 

> 실행파일

lioncho_2048.exe
0.15MB

 

> 게임 이미지

더보기
시작 화면

 

스코어 및 연산

 

칸 다차면 종료

 

 

> code

더보기
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _20200502
{
    public partial class form : Form
    {
        Random random;

        int[,] array;
        bool start = true;
        int totalScore;

        int x;
        int y;
        int randomNum1;
        int randomNum2;

        Control newNumTemp;


        public form()
        {
            InitializeComponent();

            this.Init();
            this.StartGame();

            this.TableInit();

            this.IsNumberBackgroundColor();

        }

        public void Init()
        {
            this.random = new Random();
            this.newNumTemp = new Control();
        }

        // up 버튼 입력시 해당 방향으로 재정렬
        public void UpDataSort()
        {
            int[,] newArr = new int[4, 4];

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    if (this.array[i, j] > 0)
                    {
                        for (int k = 0; k < newArr.GetLength(1); k++)
                        {
                            if (newArr[k, j] == 0)
                            {
                                if (k != 0)
                                {
                                    if (newArr[k - 1, j] == this.array[i, j])
                                    {
                                        newArr[k - 1, j] = this.array[i, j] * 2;
                                        this.totalScore += newArr[k - 1, j];
                                        break;
                                    }
                                }
                                newArr[k, j] = this.array[i, j];
                                break;
                            }
                        }
                    }
                }
            }
            this.array = newArr;
        }

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

        // down 버튼 입력시 해당 방향으로 재정렬
        public void DownDataSort()
        {
            int[,] newArr = new int[4, 4];


            for (int i = 3; i >= 0; i--)
            {
                for (int j = 3; j >= 0; j--)
                {
                    if (this.array[i, j] > 0)
                    {
                        for (int k = 3; k >= 0; k--)
                        {
                            if (newArr[k, j] == 0)
                            {
                                if (k != 3)
                                {
                                    if (newArr[k + 1, j] == this.array[i, j])
                                    {
                                        newArr[k + 1, j] = this.array[i, j] * 2;
                                        this.totalScore += newArr[k + 1, j];
                                        break;
                                    }
                                }
                                newArr[k, j] = this.array[i, j];
                                break;
                            }
                        }
                    }
                }
            }
            this.array = newArr;
        }

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

        // left 버튼 입력시 해당 방향으로 재정렬
        public void LeftDataSort()
        {
            int[,] newArr = new int[4, 4];

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    // 값있을 경우
                    if (this.array[j, i] > 0)
                    {

                        // 행 
                        for (int k = 0; k < newArr.GetLength(1); k++)
                        {

                            if (newArr[j, k] == 0)
                            {
                                if (k != 0)
                                {
                                    if (newArr[j, k - 1] == this.array[j, i])
                                    {
                                        newArr[j, k - 1] = this.array[j, i] * 2;
                                        this.totalScore += newArr[j, k - 1];
                                        break;
                                    }
                                }
                                newArr[j, k] = this.array[j, i];
                                break;
                            }
                        }
                    }
                }
            }
            this.array = newArr;
        }

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

        // right 버튼 입력시 해당 방향으로 재정렬
        public void RightDataSort()
        {
            int[,] newArr = new int[4, 4];

            for (int i = 3; i >= 0; i--)
            {
                for (int j = 0; j < 4; j++)
                {
                    // 값있을 경우
                    if (this.array[j, i] > 0)
                    {
                        // 행 
                        for (int k = 3; k >= 0; k--)
                        {

                            if (newArr[j, k] == 0)
                            {
                                if (k != 3)
                                {
                                    if (newArr[j, k + 1] == this.array[j, i])
                                    {
                                        newArr[j, k + 1] = this.array[j, i] * 2;
                                        this.totalScore += newArr[j, k + 1];
                                        break;
                                    }
                                }
                                newArr[j, k] = this.array[j, i];
                                break;
                            }
                        }
                    }
                }
            }
            this.array = newArr;
        }

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

        // 뷰테이블에 있는 데이터, 로직 배열과 동기화
        public void TableInit()
        {
            this.array = new int[4, 4];

            foreach (Control ctrl in tableLayoutPanel1.Controls)
            {
                if (ctrl is Label)
                {
                    var row = tableLayoutPanel1.GetRow(ctrl);
                    var col = tableLayoutPanel1.GetColumn(ctrl);

                    this.array[row, col] = 0;

                    // 값 있는 경우
                    if (ctrl.Text.Length > 0)
                    {
                        int myNum = int.Parse(ctrl.Text);
                        this.array[row, col] = myNum;
                    }
                }
            }
            this.IsNumberBackgroundColor();
        }


        // 뷰 라벨 테이블 비우고 데이터 배열 초기화
        public void NewTable()
        {
            foreach (Control ctrl in tableLayoutPanel1.Controls)
            {
                if (ctrl is Label)
                {
                    ctrl.Text = "";
                }
            }
            this.array = new int[4, 4];
        }

        // 게임 스타트시 초기값 발생
        public void StartGame()
        {
            this.RandomXY();
            this.RandomNum();
            tableLayoutPanel1.GetControlFromPosition(y, x).Text = randomNum2.ToString();

            this.RandomXY();
            this.RandomNum();
            tableLayoutPanel1.GetControlFromPosition(y, x).Text = randomNum1.ToString();
        }

        // 처음에 주어지는 숫자 위치 정하기
        public void RandomXY()
        {
            // 낮은 확률로 처음 주어지는 숫자 위치 중첩 방지
            while (true)
            {
                int tempX = random.Next(0, 4);
                int tempY = random.Next(0, 4);

                if (this.x != tempX && this.y != tempY)
                {
                    this.x = tempX;
                    this.y = tempY;
                    break;
                }
            }
        }


        // 처음에 주어지는 숫자 2,4 난수 발생 로직
        public void RandomNum()
        {
            while (true)
            {
                int tempNum1 = random.Next(2, 5);
                int tempNum2 = random.Next(2, 5);

                bool cheeck1 = false;
                bool cheeck2 = false;

                // 처음만 두개의 숫자 발생
                if (this.start)
                {
                    if (tempNum2 == 2 || tempNum2 == 4)
                    {
                        this.randomNum1 = tempNum2;
                        cheeck1 = true;
                    }
                }

                if (tempNum1 == 2 || tempNum1 == 4)
                {
                    this.randomNum2 = tempNum1;
                    cheeck2 = true;
                }

                if (cheeck1 && cheeck2)
                {
                    break;
                }
            }

        }

        // 턴 이후 지급되는 랜덤 숫자 생성
        public void CreateNewNum()
        {
            while (true)
            {
                this.RandomXY();
                if (this.array[this.x, this.y] == 0)
                {
                    break;
                }
            }
            this.newNumTemp.ForeColor = Color.Black;
            this.RandomNum();
            this.array[this.x, this.y] = this.randomNum2;
            tableLayoutPanel1.GetControlFromPosition(y, x).Text = this.randomNum2.ToString();

            tableLayoutPanel1.GetControlFromPosition(y, x).ForeColor = Color.IndianRed;

            this.newNumTemp = tableLayoutPanel1.GetControlFromPosition(y, x);

            logBox.Items.Add($"신규랜덤난수:[{x},{y}]:{this.randomNum2}");
        }



        // new버튼 이벤트 발생시 초기화
        public void GameReset()
        {
            this.array = new int[4, 4];
            this.start = true;
            this.totalScore = 0;


            this.ViewReset();
            this.StartGame();
            this.TableInit();
            this.SetScoreView();
        }

        // 전체 테이블 라벨 지우고, log창 지우기
        public void ViewReset()
        {
            foreach (Control ctrl in tableLayoutPanel1.Controls)
            {
                if (ctrl is Label)
                {
                    ctrl.Text = "";
                }
            }
            logBox.Items.Clear();
        }

        // sort된 배열, 뷰 테이블라벨에 재적용
        public void UpdateView()
        {
            foreach (Control ctrl in tableLayoutPanel1.Controls)
            {
                if (ctrl is Label)
                {
                    var row = tableLayoutPanel1.GetRow(ctrl);
                    var col = tableLayoutPanel1.GetColumn(ctrl);
                    ctrl.Text = "";

                    // 값 있는 경우
                    if (this.array[row, col] > 0)
                    {
                        ctrl.Text = this.array[row, col].ToString();
                    }
                }
            }
        }

        // 빈배열 있는지 체크
        public bool EndGameCheck()
        {
            foreach (var item in this.array)
            {
                if (item == 0)
                {
                    return true;
                }
            }
            return false;
        }

        // 게임 클리어 체크
        public bool ClearGameCheck()
        {
            foreach (var item in this.array)
            {
                if (item.Equals(2048))
                {
                    return true;
                }
            }
            return false;
        }

        // 연산값에 대한 뷰 컬러처리
        public void IsNumberBackgroundColor()
        {
            int checkNum = 0;
            foreach (Control ctrl in tableLayoutPanel1.Controls)
            {
                if (ctrl is Label)
                {
                    ctrl.BackColor = Color.Gainsboro;

                    if (ctrl.Text != "")
                    {
                        checkNum = int.Parse(ctrl.Text);

                        if (checkNum == 8)
                        {
                            ctrl.ForeColor = Color.WhiteSmoke;
                            ctrl.BackColor = Color.LightSalmon;
                        }
                        else if (checkNum == 16)
                        {
                            ctrl.ForeColor = Color.WhiteSmoke;
                            ctrl.BackColor = Color.LightCoral;
                        }
                        else if (checkNum == 32)
                        {
                            ctrl.ForeColor = Color.WhiteSmoke;
                            ctrl.BackColor = Color.Coral;
                        }
                        else if (checkNum >= 64)
                        {
                            ctrl.ForeColor = Color.WhiteSmoke;
                            ctrl.BackColor = Color.Tomato;
                        }
                        else
                        {
                            ctrl.BackColor = Color.Silver;
                            ctrl.ForeColor = Color.Black;
                        }
                    }

                    if (ctrl.Text == "")
                    {
                        ctrl.BackColor = Color.Silver;
                        ctrl.ForeColor = Color.Black;
                    }
                }
            }
        }

        // 스코어 뷰에 누계 적용
        public void SetScoreView()
        {
            scoreLabel.Text = this.totalScore.ToString();
        }

        // 개발시 배열 확인용 매소드
        public void ArrayPrint()
        {
            for (int i = 0; i < this.array.GetLength(0); i++)
            {
                for (int j = 0; j < this.array.GetLength(1); j++)
                {
                    Console.Write("[{0}, {1}]:{2} ㅣ", i, j, this.array[i, j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }

        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ 방향킼 버튼 이벤트 리스너 ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
        private void UpBtn_Click(object sender, EventArgs e)
        {
            if (ClearGameCheck()) { MessageBox.Show("게임 클리어!!"); }
            if (EndGameCheck())
            {
                this.UpDataSort();
                this.UpdateView();
                this.CreateNewNum();
                this.IsNumberBackgroundColor();
                this.SetScoreView();
            }
            else
            {
                MessageBox.Show("게임 종료");
            }
        }

        private void DownBtn_Click(object sender, EventArgs e)
        {
            if (ClearGameCheck()) { MessageBox.Show("게임 클리어!!"); }
            if (EndGameCheck())
            {
                this.DownDataSort();
                this.UpdateView();
                this.CreateNewNum();
                this.IsNumberBackgroundColor();
                this.SetScoreView();
            }
            else
            {
                MessageBox.Show("게임 종료");
            }
        }

        private void LeftBtn_Click(object sender, EventArgs e)
        {
            if (ClearGameCheck()) { MessageBox.Show("게임 클리어!!"); }
            if (EndGameCheck())
            {
                this.LeftDataSort();
                this.UpdateView();
                this.CreateNewNum();
                this.IsNumberBackgroundColor();
                this.SetScoreView();
            }
            else
            {
                MessageBox.Show("게임 종료");
            }
        }

        private void RightBtn_Click(object sender, EventArgs e)
        {
            if (ClearGameCheck()) { MessageBox.Show("게임 클리어!!"); }
            if (EndGameCheck())
            {
                this.RightDataSort();
                this.UpdateView();
                this.CreateNewNum();
                this.IsNumberBackgroundColor();
                this.SetScoreView();
            }
            else
            {
                MessageBox.Show("게임 종료");
            }
        }

        // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ new 버튼  ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

        // newGame 버튼 클릭시 비우고 난수 발생하기
        private void button1_Click(object sender, EventArgs e)
        {
            this.GameReset();
        }

        //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ ?? ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

    }
}

연속 출석 했을때 받는 보상을, 누적하면 추가로 주는 보너스 보상으로 생각했었다.

가장 최근에 했던 검은사막m 했던 기억이 나를 지배했다. ㄷㄷ 좀더 귀를 열고 강사님 말씀에 집중해야 할 듯

최근에 과제를 하면서, 확실이 게임 개발은 각 기능의 알고리즘을 이해하는것이 특히나 중요한 것 같다.  

 

 

> 결과

더보기
실행시킨 일자부터 28후 이벤트 종료 / 출석 / 누적 카운트 / 출석or다음날접속 시 today +1

 

2번 다음날 접속시, 하루 소요
같은 아이템 보상시 수량만 추가

 

누적 연속 출석시 추가 보상 

 

하루 소요시, 연속보상 누적 카운트는 초기화

 

만약 5일차 연속보상 수령했는데, 초기화 후 다시 누적해도 해당 연속 보상은 받을수 없다.

 

 

 

> 코드

1. Data.cs

더보기
    class EverydayData
    {
        public int id;
        public int everyday_date;
        public int everyday_item;
        public int everyday_item_amount;
    }
    class ItemData
    {
        public int id;
        public string item_name;
        public string icon_item_image;
        public int amount;
    }

 

 

2. DataManager.cs

더보기
    class DataManager
    {
        private static DataManager singleTone;

        private Dictionary<int, ItemData> dicItemData;
        private Dictionary<int, EverydayData> dicEverydataData;

        private DataManager()
        {
            this.dicEverydataData = new Dictionary<int, EverydayData>();
            this.dicItemData = new Dictionary<int, ItemData>();
        }

        public bool LoadDatas()
        {
            bool reuslt = false;
            string path = "";
            string json = "";

            try
            {
                path = "./data/everyday_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    //   Console.WriteLine(json);
                    this.dicEverydataData = JsonConvert
                        .DeserializeObject<EverydayData[]>(json)
                        .ToDictionary(v => v.id, v => v);
                }

                path = "./data/item_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicItemData = JsonConvert
                           .DeserializeObject<ItemData[]>(json)
                           .ToDictionary(v => v.id, v => v);
                }
                reuslt = true;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                throw;
            }
            return reuslt;
        }

        public static DataManager GetInstance()
        {
            if (DataManager.singleTone == null)
            {
                DataManager.singleTone = new DataManager();
                return DataManager.singleTone;
            }
            else
            {
                return DataManager.singleTone;
            }
        }

        public Dictionary<int, EverydayData> GetEverydataDatas()
        {
            return this.dicEverydataData;
        }

        public EverydayData GetEverydayData(int id)
        {
            return this.dicEverydataData[id];
        }

        public Dictionary<int, ItemData> GetItemDatas()
        {
            return this.dicItemData;
        }

        public ItemData GetItemData(int id)
        {
            return this.dicItemData[id];
        }
    }

 

 

3. App.cs

더보기
    class App
    {
        DataManager dm;
        UserInfo info;

        public static DateTime TODAY;
        DateTime endDay;


        public App()
        {
            this.Init();
            this.endDay = TODAY.AddDays(28);

            while (true)
            {
                this.Login();
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
                Console.Write("* test 입력 (1번 출석 / 2번 다음날 접속): ");
                string input = Console.ReadLine();
                Console.WriteLine();
                if (TODAY > this.endDay)
                {
                    Console.WriteLine("!!!!! 출석 이벤트 종료 !!!!!");
                    return;
                }
                this.View(input);
                Console.WriteLine();
                TODAY = TODAY.AddDays(1);
                this.info.SaveUserInfoData();

            }
        }

        public void Init()
        {
            dm = DataManager.GetInstance();
            dm.LoadDatas();
            TODAY = DateTime.Now;
            this.info = new UserInfo();
        }

        public void GetItemPrint(ItemData item)
        {
            Console.WriteLine("ㅡㅡㅡㅡ 일간 출석 보상 ㅡㅡㅡㅡ");
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            Console.WriteLine($"- {this.info.dayCount}일자 아이템 입니다. 아이템 우편으로 획득");
            Console.WriteLine($"{item.item_name}({item.amount})");
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
        }

        public void ChainDayPrint(int eventDay, ItemData chainItem, int amount)
        {
            Console.WriteLine("ㅡㅡㅡㅡ 연속 보상 ㅡㅡㅡㅡ");
            Console.WriteLine("□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□");
            Console.WriteLine($"- 누적{this.info.rewardedCount}일 입니다. 아이템 추가증정");
            Console.WriteLine($"{chainItem.item_name}({amount})");
            Console.WriteLine("□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□");
            this.info.RewardedItem(this.info.userId, chainItem);
        }


        public void View(string check)
        {
            var data = dm.GetEverydataDatas();
            List<int> list = new List<int>(data.Keys);

            if (check != "1")
            {
                Console.WriteLine("ㅡㅡㅡ 하루소요 ㅡㅡㅡ");
                Console.WriteLine($"오늘날짜:[{TODAY.Month}월{TODAY.Day}일] / 이벤트 남은일자:[{(this.endDay - TODAY).Days}일]");
                return;
            }


            foreach (var key in list)
            {
                var item = dm.GetItemData(data[key].everyday_item);
                Console.Write($"[{data[key].everyday_date}일]{item.item_name}");
                Console.Write($"({data[key].everyday_item_amount})");
                Console.Write("   ");
                // 줄바꿈
                if (data[key].everyday_date % 7 == 0) { Console.WriteLine(); }
            }
            Console.WriteLine();

            Console.WriteLine($"[출석:{this.info.dayCount}]/[누적:{this.info.rewardedCount}일] / 오늘날짜:[{TODAY.Month}월{TODAY.Day}일] / 이벤트 남은일자:[{(this.endDay - TODAY).Days}일]");

            Console.WriteLine();

            //일일 보상 ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

            // 전체 일정에서 금일 보상에 따른 아이템 찾기
            var todayRewardItemData = data.FirstOrDefault(v => v.Value.everyday_date == this.info.dayCount).Value;

            // 금일 지급할 아이템 키
            int todayRewardItemKey = todayRewardItemData.everyday_item;

            // 금일 지급할 아이템 지급 수량
            int todayRewardItemAmount = todayRewardItemData.everyday_item_amount;

            // 찾은 키로 아이템 가져오기
            ItemData todayRewardItem = dm.GetItemData(todayRewardItemKey);
            todayRewardItem.amount = todayRewardItemAmount;

            this.ItemGet(todayRewardItem, todayRewardItemAmount);

            //연속 보상 ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
            var awChack = this.info.chainDayList.Contains(this.info.rewardedCount);
            if (awChack)
            {
                switch (this.info.rewardedCount)
                {
                    case 5:
                        this.info.chainDayList.Remove(this.info.rewardedCount);
                        this.ChainDayPrint(5, dm.GetItemData(1008), 1);
                        break;
                    case 10:
                        this.info.chainDayList.Remove(this.info.rewardedCount);
                        this.ChainDayPrint(10, dm.GetItemData(1004), 200);
                        break;
                    case 20:
                        this.info.chainDayList.Remove(this.info.rewardedCount);
                        this.ChainDayPrint(20, dm.GetItemData(1004), 500);
                        break;
                    default:
                        break;
                }
            }
        }

        public void ItemGet(ItemData rewardedItem, int amount)
        {
            // 일일 보상 획득
            this.GetItemPrint(rewardedItem);
            bool reuslt = this.info.RewardedItem(this.info.userId, rewardedItem);
        }

        public void Login()
        {
            this.info.LoadUserInfoData();
        }
    }

 

4. UserInfo.cs

더보기
    class UserInfo
    {
        public string userId;
        public string rewardedDate;

        public int dayCount;
        public int rewardedCount;

        public List<int> chainDayList;

        public Dictionary<int, ItemData> dicRewardedItems;

        public UserInfo()
        {
            this.dicRewardedItems = new Dictionary<int, ItemData>();
            
        }

        public UserInfo(string userId, string rewardedDate, Dictionary<int, ItemData> dicRewardedItems)
        {
            this.userId = userId;
            this.rewardedDate = rewardedDate;
            this.dicRewardedItems = dicRewardedItems;
        }

        public bool RewardedItem(string userid, ItemData rewardedItem)
        {
            this.userId = userid;
            this.rewardedDate = App.TODAY.ToString("yyyy-MM-dd HH:mm:s"); ;
            // 같은 아이템의경우 수량만 추가
            if (!this.dicRewardedItems.ContainsKey(rewardedItem.id))
            {
                this.dicRewardedItems.Add(rewardedItem.id, rewardedItem);
            }
            else
            {
                this.dicRewardedItems[rewardedItem.id].amount += rewardedItem.amount;
                Console.WriteLine("{0}(소지수량:{1}) + {2}획득",
                    this.dicRewardedItems[rewardedItem.id].item_name,
                    this.dicRewardedItems[rewardedItem.id].amount,
                    rewardedItem.amount
                    );
                Console.WriteLine();
            }
            return this.SaveUserInfoData();
        }

        public bool SaveUserInfoData()
        {
            bool result = false;
            var json = JsonConvert.SerializeObject(this);

            try
            {
                File.WriteAllText("./info/userInfo.json", json);

                result = true;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                throw;
            }
            return result;
        }

        public void LoadUserInfoData()
        {
            DirectoryInfo folder = new DirectoryInfo("./info");
            if (!folder.Exists)
            {
                folder.Create();
            }

            var path = "./info/userInfo.json";
            try
            {
                if (File.Exists(path))
                {
                    var json = File.ReadAllText(path);
                    UserInfo readInfo = new UserInfo();
                    readInfo = JsonConvert.DeserializeObject<UserInfo>(json);
                    this.rewardedDate = readInfo.rewardedDate;
                    this.userId = readInfo.userId;
                    this.dicRewardedItems = readInfo.dicRewardedItems;
                    this.dayCount = readInfo.dayCount;
                    this.rewardedCount = readInfo.rewardedCount;
                    this.chainDayList = readInfo.chainDayList;
                }
                else
                {
                    Console.WriteLine("-신규유저입니다.");
                    Console.WriteLine("-ID는 lion 입니다.");
                    this.userId = "lion";
                    this.chainDayList = new List<int> { 5, 10, 15 };
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
                throw;
            }

            this.dayCount++;

            if (!this.RewardedCountCheck())
            {
                this.rewardedCount = 0;
            }
            this.rewardedCount++;
        }

        public bool RewardedCountCheck()
        {
            DateTime loadDate = Convert.ToDateTime(this.rewardedDate);
            if (this.rewardedDate != null)
            {
                if (App.TODAY.AddDays(-1).Day == loadDate.Day)
                {
                    return true;
                }
            }
            this.rewardedDate = App.TODAY.ToString("yyyy-MM-dd HH:mm:s");
            return false;
        }
    }

 

 

매일매일 페키지는 매일 자정 구매제한 초기화 개념

 


> App.cs

더보기
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace _20200428_1
{
    class App
    {
        Info info;
        public App()
        {
            DataManager dm = DataManager.GetInstance();

            this.Init();


            //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
            // test용 데이터 주입

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

            this.Load();
            this.info.myDia = 2000;
            this.info.myGold = 10000000;
            this.info.myLevel = 60;

            this.info.PrintInfo();
            this.PackageList();

            // 패키지 구매 테스트
            this.BuyPackage(10000);
            this.BuyPackage(10000);
            this.BuyPackage(10001);
            this.BuyPackage(10002);
            /*  
              this.BuyPackage(10000);
              this.BuyPackage(10001);
              this.BuyPackage(10002);
              this.BuyPackage(10003);
              this.BuyPackage(10004);
              this.BuyPackage(10005);
            */

            // this.everyDayPackageCount();
            this.info.Save();
        }

        public void Init()
        {
            DataManager dm = DataManager.GetInstance();

            info = new Info();

            Console.WriteLine();
            dm.LoadDatas();
        }

        // 판매 종료일 계산
        public void convertDate(string[] getDate)
        {
            DataManager dm = DataManager.GetInstance();

            System.DateTime endDate = new System.DateTime(int.Parse(getDate[0]), int.Parse(getDate[1]), int.Parse(getDate[2]));
            TimeSpan ddayDate = endDate - DateTime.Now;

            Console.Write($"-판매종료까지: ");
            if (ddayDate.Days > 0) { Console.Write($"{ddayDate.Days}일 "); };
            Console.WriteLine($"{ ddayDate.Hours }시간 { ddayDate.Minutes }분 { ddayDate.Seconds }초 남음");

        }

        //매일매일 초기화
        public void everyDayPackageCount()
        {
            Timer timaer = null;
            int FixHours = 12;
            var now = DateTime.Now;
            var scheduledTime = new DateTime(now.Year, now.Month, now.Day, FixHours, 0, 0);
            if (scheduledTime < now)
                scheduledTime = scheduledTime.AddDays(1);

            var timeout = scheduledTime - now;

            var timer = new Timer(timeout.TotalMilliseconds);
            timer.Enabled = true;
            timer.Elapsed += OnTimeEvent;

            Console.Write($"-판매종료까지: ");
            Console.WriteLine($"{ timeout.Hours }시 { timeout.Minutes }분 { timeout.Seconds }초 남음");

        }

        public void OnTimeEvent(Object source, System.Timers.ElapsedEventArgs e)
        {
            // 해당 이벤트 발생한다면 매일 자정 이후 매일매일 패키지 구매 카운트 초기화
            Console.WriteLine(e.SignalTime);
            this.info.dicBuyedPackageData[10005] = 0;
        }

        public void BuyPackage(int buyNum)
        {
            DataManager dm = DataManager.GetInstance();
            var data = dm.GetItemDatas(buyNum);

            Console.WriteLine();
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡ 구매 ㅡㅡㅡㅡㅡㅡ");
            Console.WriteLine(data.item_name);
            this.info.BuyPackage(buyNum);
        }

        public void PackageList()
        {
            DataManager dm = DataManager.GetInstance();
            Dictionary<int, ItemData> data = dm.GetAllItemDatas();
            List<int> list = new List<int>(data.Keys);

            foreach (var key in list)
            {
                var cType = dm.GetCurrencyDataById(data[key].item_type);
                var desc = string.Format(data[key].level_limit_desc, data[key].level_limit);
                string money = String.Format("{0:#,###}", data[key].price);
                string mileage = String.Format("{0:#,###}", data[key].mileage);
                string[] testdate = new string[3];

                Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
                Console.WriteLine(" *" + data[key].item_name);


                if (data[key].mileage > 0)
                {
                    Console.WriteLine($"-마일리지: {mileage}");
                }

                if (data[key].level_limit > 0) { Console.WriteLine("-" + desc); }
                Console.Write($"[{cType.name}]");
                Console.WriteLine($"-가격: {money}");
                if (data[key].everyday_package) { Console.WriteLine("★매일매일 패키지★"); }


                if (data[key].buy_end_date != "null")
                {
                    testdate = data[key].buy_end_date.Split('.');
                    this.convertDate(testdate);
                }

                if (key == 10005)
                {
                    this.everyDayPackageCount();
                }

                if (data[key].buy_limit > 0)
                {
                    Console.Write("-구매가능수량: (");
                    if (this.info.dicBuyedPackageData.ContainsKey(key))
                    {
                        this.info.count = this.info.dicBuyedPackageData[key];
                    }
                    Console.Write(this.info.count);
                    Console.WriteLine($"/{data[key].buy_limit})");
                }

            }//forEach end
        }

        public void MyinfoPrint()
        {
            Info myInfo = this.info.GetInfoData();
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 내 정보 ㅡㅡㅡㅡㅡㅡㅡㅡ");
            Console.WriteLine("[다이아:{0}][골드:{1}][마일리지:{2}][레벨:{3}]",
                myInfo.myDia, myInfo.myGold, myInfo.myLevel);
        }

        public void Load()
        {
            var path = "./info/info.json";
            if (File.Exists(path))
            {
                //파일 읽기 
                var json = File.ReadAllText("./info/info.json");

                //역직렬화 
                //이때 배열이 아니라는점 주의 
                this.info = JsonConvert.DeserializeObject<Info>(json);
                Console.WriteLine(this.info.myLevel);
            }
        }
    }
}

 

> DataManager.cs

더보기
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using Newtonsoft.Json;

namespace _20200428_1
{
    class DataManager
    {
        private static DataManager singleTone;

        private Dictionary<int, CurrencyData> dicCurrencyData;
        private Dictionary<int, ItemData> dicItemData;

        private DataManager()
        {
            this.dicCurrencyData = new Dictionary<int, CurrencyData>();
            this.dicItemData = new Dictionary<int, ItemData>();
        }

        public static DataManager GetInstance()
        {
            if (DataManager.singleTone == null)
            {
                DataManager.singleTone = new DataManager();
                return DataManager.singleTone;
            }
            else
            {
                return DataManager.singleTone;
            }
        }

        public void LoadDatas()
        {
            string json = "";
            string path = "";

            try
            {
                // 아이템 
                path = "./data/item_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicItemData = JsonConvert.DeserializeObject<ItemData[]>(json).ToDictionary(x => x.id, x => x);
                }

                // 재화
                path = "./data/currency_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicCurrencyData = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrencyData[]>(json).ToDictionary(x => x.id, x => x);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("* catch");
                Console.WriteLine(e.Message);
                throw;
            }

        } //Loaddata() end

        public CurrencyData GetCurrencyDataById(int id)
        {
            return dicCurrencyData[id];
        }

        public ItemData GetItemDatas(int id)
        {
            return this.dicItemData[id];
        }

        public Dictionary<int, ItemData> GetAllItemDatas()
        {
            return this.dicItemData;
        }

    }// class end
}

 

> Info.cs

더보기
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200428_1
{
    class Info
    {
        public int myDia; // 소지 다이아 갯수
        public int myGold; // 소지 골드 갯수
        public int myLevel; // 현재 레벨
        public int myMileage; // 현재 누적 마일리지
        public int count;

        public Dictionary<int, int> dicBuyedPackageData; // 구매한 페키지 id, 수량 추가


        public Info()
        {
            this.dicBuyedPackageData = new Dictionary<int, int>();
        }

        public Info(int myDia, int myGold, int myLevel, int myMileage, Dictionary<int, int> dicBuyedPackageData)
        {
            this.myDia = myDia;
            this.myGold = myGold;
            this.myLevel = myLevel;
            this.myMileage = myMileage;
            this.dicBuyedPackageData = dicBuyedPackageData;
        }

        public void BuyPackage(int buyNum)
        {
            DataManager dm = DataManager.GetInstance();

            ItemData data = dm.GetItemDatas(buyNum);

            // 보유 재화 확인
            if (data.item_type == 100)
            {
                if (this.myDia >= data.price)
                {
                    // 구매가능 수량 확인
                    this.PackageBuyLimitCheck(data);
                }
                else
                {
                    Console.WriteLine("구매 다이아 부족");
                }
            }

            if (data.item_type == 101)
            {

                if (this.myGold >= data.price)
                {
                    // 구매가능 수량 확인
                    this.PackageBuyLimitCheck(data);
                }
                else
                {
                    Console.WriteLine("구매 골드 부족");
                }
            }

            this.PrintInfo();
        }

        // 수매수량, 레벨 체크
        public void PackageBuyLimitCheck(ItemData data)
        {
            if (this.dicBuyedPackageData.ContainsKey(data.id))
            {
                this.count = this.dicBuyedPackageData[data.id];
            }

            // 수량 체크
            if (data.buy_limit != 0 && data.buy_limit <= this.count) { Console.WriteLine("더이상 구매불가"); return; }

            // 레벨 체크
            if (data.level_limit != 0 && data.level_limit > this.myLevel) { Console.WriteLine("레벨부족으로 구매불가"); return; }

            if (data.item_type == 100)
            {
                Console.WriteLine("-다이아");
                this.count++;
                this.myDia -= data.price;
                this.myMileage += data.mileage;
                this.dicBuyedPackageData[data.id] = this.count;
            }

            if (data.item_type == 101)
            {
                Console.WriteLine("-골드");
                this.count++;
                this.myGold -= data.price;
                this.myMileage += data.mileage;
                this.dicBuyedPackageData[data.id] = this.count;
            }
        }

        public void PrintInfo()
        {
            DataManager dm = DataManager.GetInstance();

            Console.WriteLine($"-다이아:{this.myDia} -골드:{this.myGold} -레벨:{this.myLevel} -마일리지:{this.myMileage}");

            Console.WriteLine("ㅡㅡㅡㅡㅡ 구매 이력 ㅡㅡㅡㅡ");

            if (this.dicBuyedPackageData.Count > 0)
            {
                foreach (var item in this.dicBuyedPackageData)
                {
                    Console.WriteLine($"{item.Key } {item.Value}");
                }
            }
        }

        public void Save()
        {
            try
            {
                var json = JsonConvert.SerializeObject(this);
                File.WriteAllText("./info/info.json", json);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            Console.WriteLine("데이터 저장");
        }

        public Info GetInfoData()
        {
            return this;
        }
    }
}

 

> data파일들

더보기
namespace _20200428_1
{
    class ItemData
    {
        public int id;
        public int item_type;
        public string item_name;
        public int mileage;
        public int price;
        public int level_limit;
        public string level_limit_desc;
        public int buy_limit;
        public string buy_start_date;
        public string buy_end_date;
        public bool everyday_package;
    }
}
namespace _20200428_1
{
    class CurrencyData
    {
        public int id;
        public string name;
        public int currency_type;
        public string icon_currency;
    }
}

 

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

20200505 - winForm + 2048 게임 만들기  (0) 2020.05.04
20200429 - 일일보상 + 연속보상 + Date연산  (0) 2020.05.01
20200427 - 싱글톤  (0) 2020.04.28
20200421 - File 읽기 (JSON)  (0) 2020.04.22
20200420 - List 과제  (0) 2020.04.20

> 기능 및 특징

1. 싱글톤  ManagerData.cs

2. Chatacter.cs 상속

   - Hero.cs

   - Monster.cs

3. HeroInfo.cs 저장될 데이터 클래스, 선택적 매개변수 생성자 활용

4. Data파일들

- HeroData

- ClassData

- ExpData

- GoldData

- ItemData

- MonsterData

 

> 추후 개선시 참고사항

- UI  / 기능,데이터의  명확한  역할 구분 

- 매니저클래스에 제너릭 활용

- enum 및 데이터 파일 저장 등

 

 

> JSON Data

더보기

1. class_data.json

[{
        "id": 100,
        "class_type": 0,
        "class_name": "초보자",
        "require_level": 0
    },
    {
        "id": 101,
        "class_type": 1,
        "class_name": "검사",
        "require_level": 10
    },
    {
        "id": 102,
        "class_type": 1,
        "class_name": "파이터",
        "require_level": 30
    },
    {
        "id": 103,
        "class_type": 1,
        "class_name": "크루세이더",
        "require_level": 50
    },
    {
        "id": 104,
        "class_type": 1,
        "class_name": "히어로",
        "require_level": 90
    },
    {
        "id": 105,
        "class_type": 1,
        "class_name": "하이퍼 히어로",
        "require_level": 120
    },
    {
        "id": 106,
        "class_type": 2,
        "class_name": "아처",
        "require_level": 10
    },
    {
        "id": 107,
        "class_type": 2,
        "class_name": "헌터",
        "require_level": 40
    },
    {
        "id": 108,
        "class_type": 2,
        "class_name": "레인저 ",
        "require_level": 80
    },
    {
        "id": 109,
        "class_type": 2,
        "class_name": "보우마스터",
        "require_level": 120
    },
    {
        "id": 110,
        "class_type": 2,
        "class_name": "하이퍼 보우마스터",
        "require_level": 160
    }
]

 

2. exp_data.json

[
	{
		"exp_id": 100000,
		"level": 1,
		"require_exp": 50
	},
	{
		"exp_id": 100001,
		"level": 2,
		"require_exp": 100
	},
	{
		"exp_id": 100002,
		"level": 3,
		"require_exp": 150
	},
	{
		"exp_id": 100003,
		"level": 4,
		"require_exp": 225
	},
	{
		"exp_id": 100004,
		"level": 5,
		"require_exp": 337
	},
	{
		"exp_id": 100005,
		"level": 6,
		"require_exp": 506
	},
	{
		"exp_id": 100006,
		"level": 7,
		"require_exp": 759
	},
	{
		"exp_id": 100007,
		"level": 8,
		"require_exp": 1139
	},
	{
		"exp_id": 100008,
		"level": 9,
		"require_exp": 1708
	},
	{
		"exp_id": 100009,
		"level": 10,
		"require_exp": 2562
	},
	{
		"exp_id": 100010,
		"level": 11,
		"require_exp": 3844
	}
]

 

3. gold_data.json

[{
	"id": 100,
	"name": "골드"
}]

 

4. hero_data.json

[{
    "id": 1000,
    "class_id": 100,
    "hp": 50,
    "mp": 30,
    "damage": 1.5
}]

 

5. item_data.json

[
	{
		"id": 100,
		"name": "초록 달팽이 껍질",
		"resource_name": "green_snail_shell",
		"icon_name": "ico_green_snail_shell",
		"sell_price": 1,
		"item_type": 0
	},
	{
		"id": 101,
		"name": "파란 달팽이 껍질",
		"resource_name": "bule_snail_shell",
		"icon_name": "ico_bule_snail_shell",
		"sell_price": 1,
		"item_type": 0
	},
	{
		"id": 102,
		"name": "빨간 달팽이 껍질",
		"resource_name": "red_snail_shell",
		"icon_name": "ico_red_snail_shell",
		"sell_price": 1,
		"item_type": 0
	},
	{
		"id": 103,
		"name": "매소 (소 )",
		"resource_name": "meso_small",
		"icon_name": "ico_meso_small",
		"sell_price": 0,
		"item_type": 4
	},
	{
		"id": 104,
		"name": "매소 (중)",
		"resource_name": "meso_midium",
		"icon_name": "ico_meso_midium",
		"sell_price": 0,
		"item_type": 4
	},
	{
		"id": 105,
		"name": "매소 (대)",
		"resource_name": "meso_large",
		"icon_name": "ico_meso_large",
		"sell_price": 0,
		"item_type": 4
	}
]

 

6. monster_data.json

[
  {
    "id": 1000,
    "name": "초록 달팽이",
    "hp": 25,
    "damage": 2.5,
    "exp": 1,
    "drop_item_id": 100
  },
  {
    "id": 1001,
    "name": "파란 달팽이",
    "hp": 25,
    "damage": 2.8,
    "exp": 2,
    "drop_item_id": 101
  },
  {
    "id": 1002,
    "name": "빨간 달팽이",
    "hp": 25,
    "damage": 3,
    "exp": 3,
    "drop_item_id": 102
  },
  {
    "id": 2000,
    "name": "머쉬맘",
    "hp": 1000,
    "damage": 8,
    "exp": 10,
    "drop_item_id": 103
  }
]

 

 

> Code

1. Data 클래스

더보기
    class MonsterData
    {
        public int id;
        public string name;
        public int hp;
        public float dmage;
        public int exp;
        public int drop_item_id;

    }
    class ItemData
    {
        public int id;
        public string name;
        public string resource_name;
        public string icon_name;
        public int sell_price;
        public int item_type;

    }
class HeroData
    {
        public int id;
        public int class_id;
        public int hp;
        public int mp;
        public float damage;

        public HeroData(int id, int class_id, int hp, int mp, float damage)
        {
            this.id = id;
            this.class_id = class_id;
            this.hp = hp;
            this.mp = mp;
            this.damage = damage;
        }
    }
    class GoldData
    {
        public int id;
        public string name;
    }
    class ExpData
    {
        public int exp_id;
        public int level;
        public int require_exp;
    }
    class ClassData
    {
        public int id;
        public int class_type;
        public string class_name;
        public int require_level;

    }

    class Character
    {
        public Character()
        {
        }
        public virtual void Attack(Character target) { }

        public virtual void Hit(float damamge) { }

        public virtual void Die() { }
    }

 

 

2. Info 클래스

더보기
    class HeroInfo
    {
        public string name;
        public int level;
        public int classType; // 직업타입
        public int classGrade; // 등급 id 검사or 파이터등 등급을 말하는 것?
        public float damage;
        public int hp;
        public int mp;
        public int exp;
        public int gold;

        // 선택적 매개변수 뒤쪽에 배치 필요
        public HeroInfo(string name, int hp, int mp, float damage,
             int level = 1, int classType = 0, int classGrade = -1, int exp = 0, int gold=0)
        {
            this.name = name;
            this.level = level;
            this.classType = classType;
            this.classGrade = classGrade;
            this.hp = hp;
            this.mp = mp;
            this.damage = damage;
            this.exp = exp;
            this.gold = gold;
        }
    }

 

3. 싱글톤 매니저 클래스

더보기
    class DataManager
    {
        private static DataManager singleTone;

        private Dictionary<int, HeroData> dicHeroData;
        private Dictionary<int, ClassData> dicClassData;
        private Dictionary<int, ExpData> dicExpData;
        private Dictionary<int, GoldData> dicGoldData;
        public Dictionary<int, ItemData> dicItemData;
        private Dictionary<int, MonsterData> dicMonsterData;

        public static DataManager GetInstance()
        {

            if (DataManager.singleTone == null)
            {
                DataManager.singleTone = new DataManager();
                return DataManager.singleTone;
            }
            else
            {
                return DataManager.singleTone;
            }

        }// GetInstance end;

        public void LoadDatas()
        {
            string json = "";
            string path = "";

            try
            {
                // 영웅 생성
                path = "./data/hero_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicHeroData = JsonConvert.DeserializeObject<HeroData[]>(json).ToDictionary(x => x.id, x => x);
                }

                // 몬스터 생성
                path = "./data/monster_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicMonsterData = JsonConvert.DeserializeObject<MonsterData[]>(json).ToDictionary(x => x.id, x => x);
                }

                // 아이템 생성
                path = "./data/item_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicItemData = JsonConvert.DeserializeObject<ItemData[]>(json).ToDictionary(x => x.id, x => x);
                }

                // 전직 데이터
                path = "./data/class_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicClassData = JsonConvert.DeserializeObject<ClassData[]>(json).ToDictionary(x => x.id, x => x);
                }

                // 경험치 데이터
                path = "./data/exp_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicExpData = JsonConvert.DeserializeObject<ExpData[]>(json).ToDictionary(x => x.exp_id, x => x);
                }

                // 골드 데이터
                path = "./data/gold_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicGoldData = JsonConvert.DeserializeObject<GoldData[]>(json).ToDictionary(x => x.id, x => x);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        public HeroData GetCharacterDataById(int id)
        {
            return this.dicHeroData[id];
        }

        public MonsterData GetMonsterDataById(int id)
        {
            return this.dicMonsterData[id];
        }

        public ExpData GetExpDataByLevel(int level){
            var result = this.dicExpData.FirstOrDefault(v => v.Value.level == level).Value;
            return result;
        }

        public ClassData GetClassDataByClassType(int classType){ 
            var result = this.dicClassData.FirstOrDefault(v => v.Value.class_type == classType).Value;
            return result;
        }

        public GoldData GetGoldDataById(int id){
            return this.dicGoldData[id];
        }

        public ItemData GetItemDataById(int dropItemId){
            return this.dicItemData[dropItemId];
        }
    }

 

4. Monster / Hero 클래스

더보기
    class Monster : Character
    {
        public int id;
        public string name;
        public float hp;
        public float damage;
        public int exp;
        public int drop_item_id;
        public float maxHp;

        public Monster(MonsterData data)
        {
            this.id = data.id;
            this.name = data.name;
            this.hp = data.hp;
            this.damage = data.dmage;
            this.exp = data.exp;
            this.drop_item_id = data.drop_item_id;
            this.maxHp = data.hp;

            Console.WriteLine(this.name + " 이 생성되었습니다.");
        }

        public override void Attack(Character target)
        {
            Console.WriteLine(target);
            target.Hit(this.damage);
        }

        public override void Hit(float damage)
        {
            Console.WriteLine("몬스터 hit");
            this.hp -= damage;
            if (this.hp <= 0)
            {
                this.Die();
            }
        }

        public override void Die()
        {
            Console.WriteLine("몬스터가 죽었습니다.");
        }

        public bool IsDie() {
            this.hp = 0; //강제 죽임 test
            if (this.hp <= 0) {
                return true;
            }
            return false;
        }
    }

    class Hero : Character
    {
        // 데이터 변경과 에니메이션 담당 -> 외부에 결과 전달(App())
        public HeroInfo info;
        public Hero()
        {
            Console.WriteLine("영웅이 생성되었습니다.");
        }

        public void Init(HeroInfo info)
        {
            this.info = info;
        }

        public override void Attack(Character target)
        {
            target.Hit(this.info.damage);
        }

        public override void Hit(float damage)
        {
            Console.WriteLine($"{this.info.name}이  {damage} 피해를 입어습니다.");
        }

        public override void Die()
        {
           this.info.hp = 0;
            Console.WriteLine("- game over 주인공이 죽었습니다.");
        }

        // 경험치 획득
        public void GetExp(int getExp) {
            this.info.exp += getExp;
            Console.WriteLine($"{this.info.exp} 경험치 획득");
            Console.WriteLine();
        }

        // 경험치 확인
        public void CheckExp(Hero hero) {
          var dataManager = DataManager.GetInstance();
          var exp = hero.info.exp; // 현재 경험치

          //현재 레벨로 가져온 exp데이터
          var expData = dataManager.GetExpDataByLevel(hero.info.level); 
            
          //다음레벨 exp데이터 
          var nextData = dataManager.GetExpDataByLevel(hero.info.level+1); 

          // 레벨업 체크
          if(exp >= expData.require_exp){
             this.LevelUp(hero);
          }else{
            Console.WriteLine($"-Lev{hero.info.level} / {hero.info.exp} -> -Lev{nextData.level} / {expData.require_exp} 필요");
          }
            Console.WriteLine();
        }

        // 레벨 업
        public void LevelUp(Hero hero)
        {
            // 전직 여부 체크
            var dataManager = DataManager.GetInstance();

            if(hero.info.classType == 0 ){ // 초보자 일경우
                Console.WriteLine("- 축하합니다. 전직이 가능합니다.");
                this.ClassChange();
                this.HeroPrint();
            }else{
                // 레벨업
                Console.WriteLine("- 레벨이 올랐습니다.");
                this.UpGrage();
                this.HeroPrint();
            }
        }

        // 스텟 상향
        public void UpGrage(){
             var dataManager = DataManager.GetInstance();

              var classData = dataManager.GetClassDataByClassType(this.info.classGrade+1);

              this.info.classGrade = classData.id;
              this.info.name = classData.class_name;
              this.info.level +=1;
        }

        public void HeroPrint(){
            var hero = this.info;
            Console.WriteLine($"name:{hero.name}/ Lev:{hero.level} / (hp:{hero.hp}/hp:{hero.mp})");
        }

        // 전직
        public void ClassChange()
        {
            var dataManager = DataManager.GetInstance();
            var choiceClass1 = dataManager.GetClassDataByClassType(1);
            var choiceClass2 = dataManager.GetClassDataByClassType(2);

            Console.WriteLine($"1.{choiceClass1.class_name} / 2.{choiceClass2.class_name} 선택");
            Console.WriteLine("1번 선택");
            var userInput=1;

            switch (userInput)
	        {
                case 1:
                    Console.WriteLine("검사를 선택하셨습니다.");
                    this.info.name = choiceClass1.class_name;
                    this.info.classType = choiceClass1.class_type;
                    this.info.classGrade = choiceClass1.id; // 검사 101
                    this.info.level +=1;
                    break;
                case 2:
                    Console.WriteLine("아처를 선택하셨습니다.");
                    this.info.name = choiceClass2.class_name;
                    this.info.classType = choiceClass2.class_type;
                    this.info.classGrade = choiceClass2.id; // 아처 10
                    this.info.level +=1;
                    break;
		        default:
                    break;
	        }
                    Console.WriteLine();
        }

        //아이템 획득
        public void PickItem(Monster target){
            var dataManager = DataManager.GetInstance();
            var getItem = dataManager.GetItemDataById(target.drop_item_id);

            Console.WriteLine($"- 아이템획득: {getItem.name} / 판매가격:{getItem.sell_price} / {getItem.resource_name}");
            Console.WriteLine();
        }

        //골드 획득
        public void PickGold(int id){
            var dataManagere = DataManager.GetInstance();
            GoldData goldData = dataManagere.GetGoldDataById(id);

            this.info.gold += goldData.id;

            Console.WriteLine($"- {goldData.name}({goldData.id}) 획득!");
            Console.WriteLine();
        }
    }

 

5. App 클래스

더보기
    class App
    {
        public App()
        {
            // 데이터 로드
            // 영웅 생성
            // 몬스터 생성
            // 몬스터 공격
            // 몬스터 처치
            // 아이템 드랍
            // 경험치, 아이템 획득
            // 레벨업
            // 전직

            var dataManager = DataManager.GetInstance();
            dataManager.LoadDatas();


            Hero hero  = this.CreateDefaultHero();
            Monster monster = this.CreateMonster(1000);

            //몬스터 공격
            hero.Attack(monster);

            Console.WriteLine($"({monster.hp}/{monster.maxHp})" );

            // 죽임
            monster.Die();
            monster.IsDie();


            // 경험치 획득 
            if (monster.IsDie())
            {
                hero.GetExp(monster.exp);
                hero.CheckExp(hero);

                // 강제 레벨업 - 전직
                hero.LevelUp(hero);

                // 아이템 획득
                hero.PickItem(monster);

                // 골드획득 - 몬스터 고유 id 전달하여 해당 수치만큼 골드 수급
                hero.PickGold(100);
            }
        }


        
        public Monster CreateMonster(int id)
        {
            var monsterData = DataManager.GetInstance().GetMonsterDataById(id);

            return new Monster(monsterData);
        }

        public Hero CreateDefaultHero()
        {
            var characterData = DataManager.GetInstance().GetCharacterDataById(1000);

            var heroInfo = new HeroInfo("홍길동", characterData.hp, characterData.mp, characterData.damage);
            Hero hero = new Hero();
            hero.Init(heroInfo);
            Console.WriteLine(hero.info.name + " 님이 입장하셨습니다.");
            return hero;
        }
    }

 


 

> File.ReadAllText() -- 모든 문자열 읽기

더보기
 public void ReadAllTextTest()
        {
            string path = "./cookie_data.json";

            string json = File.ReadAllText(path);

            Console.WriteLine(json);

            CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(json);

            foreach (var item in arrCookieDatas)
            {
                Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
            }
        }

 

> File.ReadAllLines() -- 문자열 한줄씩 읽어오기

더보기
 public void ReadAllLinesTest()
        {
            string path = "./cookie_data.json";

            string[] textValue = File.ReadAllLines(path);

            string fullTextValue = "";
            foreach (var item in textValue)
            {
                fullTextValue += item;
            }

            Console.WriteLine(fullTextValue);

            CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(fullTextValue);
            foreach (var item in arrCookieDatas)
            {
                Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
            }
        }

 

> File.OpenRead() / new StreamReader() -- 파일 읽어와 textReader 스트림에서 문자열 읽기

더보기
public void FileStreamTest()
        {
            string path = "./cookie_data.json";

            FileStream fs = File.OpenRead(path); 
            StreamReader sr = new StreamReader(fs);

            // sr.ReadToEnd() 스트림 끝까지 모든 문자를 읽기
            CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(sr.ReadToEnd());

            foreach (var item in arrCookieDatas)
            {
                Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
            }
        }

 

> File.ReadAllLines()

더보기

            string[] jsonLines = File.ReadAllLines(fileDir);      


 

> CookieData.cs

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

namespace _20200421_json
{
    class CookieData
    {
        public int id;
        public string name;
        public int grade;
    }
}

            > 바닥 수량보다 많이 입력시, 바닥 최대수량 획득 후 바닥 아이템 목록에서 제거

 

> 수량 반영

 


> App 생성자

더보기
        List<Item> dropItemList;
        Inventory inventory;


        public App()
        {
            ListApp3();
        }

 

> ListApp3()

더보기
        public void ListApp3()
        {
            this.dropItemList = new List<Item>();

            this.dropItemList.Add(new Item("장검", 10));
            this.dropItemList.Add(new Item("단검", 2));
            this.dropItemList.Add(new Item("활", 5));

            string dropItemName;
            int dropItemAmount;

            this.inventory = new Inventory();

            while (true)
            {
                PrintDropList(dropItemList);
                Console.WriteLine();

                Console.Write("아이템을 획득하려면 명령어를 입력해주세요: ");
                var input = Console.ReadLine();

                string[] cInput = input.Split(' ');

                dropItemName = cInput[0];
                dropItemAmount = int.Parse(cInput[1]);

                GetItemList(dropItemName, dropItemAmount);

                this.inventory.PrintAllItems();

            }
        }

 

> PrintDropList()

더보기
        public void PrintDropList(List<Item> list)
        {

            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            Console.WriteLine("길바닥에 떨어져있는 아이템");
            foreach (var item in list)
            {
                if (item != null)
                {
                    Console.WriteLine($"{item.name}, {item.amount}");
                }
            }
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            Console.WriteLine();
        }

 

> GetItemList()

더보기
        public void GetItemList(string dropItemName, int dropItemAmount)
        {
            var findDropitem = this.dropItemList.Find(v => v.name == dropItemName);

            if (findDropitem == null)
            {
                Console.WriteLine(">입력한 아이템은 획득 할 수 없습니다.");
                Console.WriteLine();
                return;
            }

            // 바닥에 있는 수량보다 많이 획득 할 경우
            if (findDropitem.amount <= dropItemAmount)
            {
                Console.WriteLine($"최대 {findDropitem.amount}개 를 획득했습니다.");
                this.inventory.Add(new Item(dropItemName, findDropitem.amount));
                this.dropItemList.Remove(findDropitem);
            }
            else
            {
                this.inventory.Add(new Item(dropItemName, dropItemAmount));
                findDropitem.amount -= dropItemAmount;
            }
        }

 

> 레시피 구매(습득)

> 구매(습득)한 레시피 확인

> 레시피의 재료 확인 / 레시피 배우기

> 배운 레시피 요리 목록

> 요리 하기(가방x - 재료확인 후 요리시작)


 

> Food.cs

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

namespace _20200417_Recipe
{
    class Food
    {
        public string name;

        public Food(string name)
        {
            this.name = name;
        }
    }
}

 

> Recipe.cs

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

namespace _20200417_Recipe
{
    class Recipe
    {
        public string name; // 레시피 이름(만들어질 음식 이름)
        public FoodIngredient[] arrFoodIngredientNames;

        public Recipe(string name, FoodIngredient[] arrFoodIngredientNames)
        {
            this.name = name;
            this.arrFoodIngredientNames = arrFoodIngredientNames;
        }

        public string GetName()
        {
            return "조리법: " + this.name;
        }
    }
}

 

> FoodIngredient

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

namespace _20200417_Recipe
{
    class FoodIngredient
    {
        public string name;
        public int amount;

        public FoodIngredient(string name, int amount)
        {
            this.name = name;
            this.amount = amount;
        }
    }
}

 

> Character.cs

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

namespace _20200417_Recipe
{
    class Character
    {
        public string name; //캐릭터 이름
        public Recipe[] arrRecipe; //소지중인 레시피들
        public Recipe[] arrCookRecipe; //소지중인 레시피들 
        public int recipeIndex; // 레시피 배열의 인덱스
        public int cookRecipeIndex; // 레시피 배열의 인덱스

        public Character(string name)
        {
            this.name = name;
            this.arrRecipe = new Recipe[10];
            this.arrCookRecipe = new Recipe[10];
            Console.WriteLine($"{this.name}이 생성되었습니다.");
        }

        public void PickRecipe(Recipe recipe)
        {
            Console.WriteLine("-- 구매 --");
            Console.WriteLine($"{recipe.name}");
            this.arrRecipe[this.recipeIndex++] = recipe;
        }

        public void UseRecipe(string recipe)
        {
            Recipe[] newArr = new Recipe[10];
            int idx = 0;

            for (int i = 0; i < this.arrRecipe.Length; i++)
            {
                if (this.arrRecipe[i].name == recipe)
                {
                    this.arrCookRecipe[this.cookRecipeIndex++] = this.arrRecipe[i];
                    Console.WriteLine(recipe + "레시피를 배웠습니다.");
                    this.arrRecipe[i] = null;

                    foreach (var item in arrRecipe)
                    {
                        if (item != null)
                        {
                            newArr[idx++] = item;
                        }
                    }
                    this.arrRecipe = newArr;
                    this.recipeIndex = -1;

                    break;
                }
            }
        }

        public Recipe[] PrintMyRecipe()
        {
            Console.WriteLine("** 소지하고있는 레시피 **");
            foreach (var item in this.arrRecipe)
            {
                var idx = Array.IndexOf(this.arrRecipe, item);
                if (item != null)
                {
                    Console.WriteLine($"{idx + 1}.{item.name}");
                }
            }
            return this.arrRecipe;
        }

        public Recipe[] PrintCookRecipe()
        {
            Console.WriteLine("** 요리가능한 레시피 **");
            foreach (var item in this.arrCookRecipe)
            {
                var idx = Array.IndexOf(this.arrCookRecipe, item);
                if (item != null)
                {
                    Console.WriteLine($"{idx}.{item.name}");
                }
                else
                {
                    Console.WriteLine("없음");
                }
            }
            return this.arrCookRecipe;
        }


        public Recipe infoRecipe(string recipeName, Recipe[] checkRecipeList)
        {
            Recipe recipe = null;
            foreach (var item in checkRecipeList)
            {
                if (item != null)
                {
                    if (item.name == recipeName)
                    {
                        return item;
                    }
                }
            }
            return recipe;
        }


        public string Cook(string recipeName)
        {
            // 재료 확인
            // 재료 수량 확인
            foreach (var item in this.arrCookRecipe)
            {
                if (item != null)
                {
                    if (item.name == recipeName)
                    {
                        Console.Write("-- 재료를 사용합니다: ");
                        foreach (var ingredient in item.arrFoodIngredientNames)
                        {
                            if (ingredient != null)
                            {
                                Console.Write($"[{ingredient.name}({ingredient.amount})] ");
                            }
                        }
                        Console.WriteLine();
                    }
                }
            }
            Console.WriteLine(recipeName + "를 요리합니다.");
            return "";
        }
    }
}

 

> App.cs

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

namespace _20200417_Recipe
{
    class App
    {
        Character hong;
        FoodIngredient[] arrFoodIngredientNames;
        Recipe recipe;
        string input = "";
        bool buyed1 = false;
        bool buyed2 = false;

        public App()
        {
            this.hong = new Character("홍길동");
            while (true)
            {
                MainView();
                Console.Write(">입력: ");
                input = Console.ReadLine();
                SubView(input);
            }
        }

        public void MainView()
        {
            Console.WriteLine();
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            Console.WriteLine("[1.요리하기] [2.레시피 구매] [3.가방 레시피 확인]");
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
        }

        public void SubView(string inputNum)
        {
            switch (inputNum)
            {
                case "1":
                    Recipe[] result = this.hong.PrintCookRecipe();
                    CookRecipe(result);
                    break;
                case "2":
                    BuyRecipe();
                    break;
                case "3":
                    Recipe[] arrRecipeList = this.hong.PrintMyRecipe();
                    Console.WriteLine();
                    Console.WriteLine("> [1.레시피 재료확인] [2.요리배우기] [9.돌아가기]");
                    Console.Write("> 입력: ");
                    input = Console.ReadLine();
                    if (input == "9") { Console.WriteLine(">이전으로 돌아갑니다!"); return; }
                    if (input == "1")
                    {
                        Console.Write("> 확인하려는 요리 번호를 입력해주세요: ");
                        input = Console.ReadLine();
                        infoRecipe(input, arrRecipeList);
                    }
                    Console.WriteLine();
                    Console.WriteLine("> 배우시려면 해당 번호 입력, [9.돌아가기]");
                    Console.Write(">입력: ");
                    input = Console.ReadLine();
                    if (input == "9") { Console.WriteLine(">이전으로 돌아갑니다!"); return; }
                    UseRecipe(input, arrRecipeList);
                    break;
                default:
                    break;
            }
        }

        public void infoRecipe(string input, Recipe[] checkRecipeList)
        {
            int check = int.Parse(input);

            Recipe result = hong.infoRecipe(checkRecipeList[check - 1].name, checkRecipeList);
            if (result != null)
            {
                Console.WriteLine("> 찾은 요리정보 <");
                Console.Write($"{result.name} : 필수재료--");
                foreach (var item in result.arrFoodIngredientNames)
                {
                    Console.Write($"[{item.name}({item.amount})] ");
                }
            }
            else
            {
                Console.WriteLine("찾는 요리 없음");
            }
            Console.WriteLine();
        }

        public void CookRecipe(Recipe[] arrCookRecipe)
        {
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
            Console.WriteLine("> 요리시려면 해당 번호 입력, [9.돌아가기]");
            Console.Write("> 입력: ");
            input = Console.ReadLine();
            if (input == "9") { Console.WriteLine(">이전으로 돌아갑니다!"); return; }
            switch (input)
            {
                case "0":
                    if (arrCookRecipe[0] == null) { return; }
                    this.hong.Cook(arrCookRecipe[0].name);

                    break;
                case "1":
                    if (arrCookRecipe[1] == null) { return; }
                    this.hong.Cook(arrCookRecipe[1].name);

                    break;
                default:
                    Console.WriteLine("> 없는번호입니다.");
                    break;
            }
            Console.WriteLine();
        }

        public void UseRecipe(string input, Recipe[] arrRecipeList)
        {
            switch (input)
            {
                case "1":
                    if (arrRecipeList[0] == null) { return; }
                    this.hong.UseRecipe(arrRecipeList[0].name);
                    break;
                case "2":
                    if (arrRecipeList[1] == null) { return; }
                    this.hong.UseRecipe(arrRecipeList[1].name);
                    break;
                default:
                    Console.WriteLine("> 없는번호입니다.");
                    break;
            }
            Console.WriteLine();
        }


        public void BuyRecipe()
        {
            FoodIngredient foodIngredient1;
            FoodIngredient foodIngredient2;

            Console.WriteLine("> [1.햄버거] [2.괴물 오믈렛]");
            Console.Write(">입력: ");
            input = Console.ReadLine();
            switch (input)
            {
                case "1":
                    if (!buyed1)
                    {
                        // 기본 레시피1 생성
                        foodIngredient1 = new FoodIngredient("쇠고기 패티", 1);
                        foodIngredient2 = new FoodIngredient("빵", 1);

                        this.arrFoodIngredientNames = new FoodIngredient[2];
                        this.arrFoodIngredientNames[0] = foodIngredient1;
                        this.arrFoodIngredientNames[1] = foodIngredient2;
                        this.recipe = new Recipe("햄버거", this.arrFoodIngredientNames);
                        this.hong.PickRecipe(this.recipe);
                        this.buyed1 = true;
                    }
                    else
                    {
                        Console.WriteLine("> 해당 레시피는 더이상 구매 불가");
                    }
                    break;
                case "2":
                    if (!buyed2)
                    {
                        // 기본 레시피2 생성
                        foodIngredient1 = new FoodIngredient("거대한 알", 1);
                        foodIngredient2 = new FoodIngredient("독특한 양념", 1);

                        this.arrFoodIngredientNames = new FoodIngredient[2];
                        this.arrFoodIngredientNames[0] = foodIngredient1;
                        this.arrFoodIngredientNames[1] = foodIngredient2;
                        this.recipe = new Recipe("괴물 오믈렛", this.arrFoodIngredientNames);
                        this.hong.PickRecipe(this.recipe);
                        this.buyed2 = true;
                    }
                    else
                    {
                        Console.WriteLine("> 해당 레시피는 더이상 구매 불가");
                    }
                    break;
                default:
                    break;
            }
            Console.WriteLine();
        }
    } //class end
}

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

20200421 - File 읽기 (JSON)  (0) 2020.04.22
20200420 - List 과제  (0) 2020.04.20
20200415 - 아이템 생성, 검색, 꺼내기, 출력 과제  (0) 2020.04.16
20200414 - 테란~아카데미까지  (0) 2020.04.14
20200413 - 슈팅 게임  (0) 2020.04.13

 

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

가상 캐릭터 이동 및 획득

 

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